try-except
Lesson 3 of 16 in Coddy's Exception Handling in Python course.
The try-except block in python is used to catch and handle Exceptions. Below is the basic structure of try-except block.
try:
statement 1
statements which can cause error
statement 3
except [ExceptionName]:
code for exception handling - Python runs the code from try block.
- If it encounters Exception, the code execution will jump to except block. Rest of lines from try block will not be executed (statement 3 in above case).
- If no Exception occurs, try block will be executed completely and except block will be skipped.
try block:
- Block containing code in which Exception can occur.
except block:
- Block where you take necessary actions if Exception occurs.
Example:
try:
a = int(input())
b = int(input())
div = a/b
print("Division is:",div)
except ZeroDivisionError:
print("Cannot divide by zero")
print("Rest of code")This program will run perfectly if user enters non-zero for b.
If user enters 0 for b, 'a/b' will cause ZeroDivisionError and control will go to except block.
It will print "Cannot divide by zero" message on console and rest of code will be executed. We avoided program termination here by using try-except
Challenge
EasyAbove program will cause 'ValueError' if user enters non numeric value for any input.
Write a program to handle this Exception and print 'Not a Number' message on console.
Try it yourself
a = int(input())
b = int(input())
div = a/b
print("Division is:",div)
#Handle exception hereAll lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks2Exception Handling
try-exceptelseFinallyPrinting Exception messagePrinting Exception NameHandling Multiple Exceptionssys module for information