Exceptions can be handled by three ways
- Handling a raised Exception
- Raise Exception
- Use of assert to handle Exception
Handling a raised Exception
The try and except block in python is used to catch and handle exceptions. Python executes the code following try statement as a normal part of the program. The code that follows the except statement is he program’s response to any exceptions in the preceding try clause
Working of try and except
try:
run this code
except:
Execute this code when there is an exception
- When syntactically correct code runs into an error, Python will throw an exception error
- The exception error will crash the program if it is unhandled.
- The except clause determines how your program responds to exceptions
Use of try and except
Syntax
try:
# Block of code that causes exception
except:
#Execute this code when there is an exception in try block
Example
try:
print(x)
except:
print("An exception occured")
Output
Description
Since x is not defined or it does not have any value assigned to it, the statement in try block raises an exception. Since try block gives an error, except block is executed
Multiple exceptions (more than one except block)
Many exceptions block can be given to handle different type of errors
Syntax
try:
# Block of code that causes exception
except <Error 1>:
# Block of code if the statement in try produces Error1
except <Error 2>:
# Block of code if the statement in try produces Error 2
….
except <Error n>:
# Block of code if the statement in try produces Error n
except:
#Execute this code when there is an exception in try block
Example
try:
x = '2' + 2
except NameError:
print("Variable z is not defined")
except TypeError:
print("TypeError")
Output
Description
Since x is assigned with adding string and integer it leads to error. The error in try block is TypeError which raises an exception and thus the except block intended for TypeError is executed
Use of try, except, else
Syntax
try:
# Block of code that causes exception
except <Error 1>:
# Block of code if the statement in try produces Error1
except <Error 2>:
# Block of code if the statement in try produces Error 2
….
except <Error n>:
# Block of code if the statement in try produces Error n
else:
#block of code to be executed when no error is raised by try block
except:
#Execute this code when there is an exception in try block
Example
try:
print("I like Python")
except NameError:
print("Variable z is not defined")
except TypeError:
print("TypeError")
else:
print("Execute when no error in try block")
Output
Description
When the try block does not produce any error, then else part will be executed.
Use of try, except, finally
The finally block will be executed regardless of try block raises an exception or not. This can be useful to close objects and clean resources
Syntax
try:
# Block of code that causes exception
except <Error 1>:
# Block of code if the statement in try produces Error1
except <Error 2>:
# Block of code if the statement in try produces Error 2
….
except <Error n>:
# Block of code if the statement in try produces Error n
else:
#block of code to be executed when no error is raised by try block
finally:
#block of code that executes always regardless of whether try block raises an exception or not
except:
#Execute this code when there is an exception in try block
Example
try:
print(z)
except NameError:
print("Variable z is not defined")
except TypeError:
print("TypeError")
else:
print("Execute when no error in try block")
finally:
print("I ll execute always regardless of try block raises an exception or not")
Output
Description
When the try block does not produce any error, then else part will be executed.
Regardless of try block produces an error or not, always finally will be executed. Here try block produces name error as z is undefined, then also the statement in finally will be executed
Raising an Exception
An expression can be raised is a condition occurs. Keyword raise is used to define the exception. Followed by raise specify error type and text to show to the user
Syntax
if (condition):
raise <Error Type>
Example
mark1 = int(input("Enter mark:"))
if(mark1 < 0 or mark1 > 100):
raise ValueError("Mark is invalid")
else:
print("Mark is valid")
Output 1
Output 2
Use of assert to handle Exception
- An assertion is like a checkpoint in a program that can be turned on or off while testing the program
- Assertions are carried out by assert statement
- When an assert statement is executed, python evaluates the accompanying expression which is true. If the expression is evaluated to false then python raises an AssertionError exception
Syntax
assert Expression[,Arguments]
- If the assertion fails, Python uses argument as the AssertionError.
- AssertionError exceptions can be caught and handled like any other exception using try – except statement but if not handled they will terminate the program and produce a traceback
Example
mark1 = int(input("Enter mark:"))
assert(mark1 >= 0 and mark1 <= 100), "Mark is Invalid"
Output
Views: 0