Exception Handling
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program.
Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
Example: Let us try to access the array element whose index is out of bound and handle the corresponding exception.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output:
Second element = 2
An error occurred
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are
try:
# statements
except IndexError:
# statements
except ValueError:
# statements
Example: Catching specific exception in Python
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Output:
NameError Occurred and Handled
Try with Else Clause
In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
Example: Try with else clause
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Raise an exception
you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise
keyword.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output:
Traceback (most recent call last):
File "code.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
Last updated