Exception Handling
Exception Handling
• When writing a program we more often than not will encounter errors.
• Error caused by not following the proper structure (syntax) of the
language is called syntax error parsing error.
>>> if a<3
Syntax Error: invalid syntax
• We can notice here that a colon is missing in the if statement.
• Errors can also occur at runtime and these are called exceptions
• They occur for example
– When a file we try to open does not exist (FileNotFoundError)
– Dividing a number by Zero (ZeroDivisionError)
– Module we try to import is not found (ImportError) etc.
• Whenever these type of runtime error occur, Python creates an exception
object. If not handled properly it prints a traceback to that error along
with some details about why that error occurred.
Exception
>>> 1/0
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> open('i.txt')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
open('i.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'i.txt'
Built-in Exceptions
• An exception is a value (object) that is raised (“thrown”) signaling that an
unexpected or “exceptional” situation has occurred.
• Python contains a predefined set of exceptions referred to as Standard
Exceptions.
Exceptions Description
ImportError Raised when an import (or from … import) statement fails
IndexError Raised when a sequence index out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an
object of inappropriate type
ValueError Raised when a built in operation or function is applied to
an appropriate type, but of inappropriate value
IOError Raised when an input/output operation fails (eg: “file not
found”)
Standard Exceptions
• The standard exceptions are defined within the exceptions module of the
python standard library, which is automatically imported into python programs.
• We have seen a number of these exceptions before in our programming.
• Raising an exception is a way for a function to inform its client a problem has
occurred that the function itself cannot handle.
Example 3:
import sys
try: OUTPUT:
i=1/0
print("i = ",i) <class 'ZeroDivisionError'> occured.
except: After division
print(sys.exc_info()[0]," occured.")
print("After division")
Exception Handling - Example
• Python don’t just handle exceptions if they occur immediately in the try
block, but also if they occur inside functions that are called in the try
block.
Example 4:
try:
func()
print("Inside try block")
except:
print(sys.exc_info()[0]," occured.")
print("After function call inside main module")
Catch Multiple Exceptions
• We can define as many except blocks as we want to catch and handle
specific exceptions.
Example 4:
try: OUTPUT:
print(int('45.6'))
except (ZeroDivisionError, ValueError): Attempt to divide by zero
print("Attempt to divide by zero")
except: ZeroDivisionError, ValueError
print("Something else went wrong")
The Else Clause
• The try except block has an optional else clause.
• The else clause is executed only if no exceptions are raised
Example:
try:
x = 1/2 x = 0.5
print("x = ",x) Nothing went wrong
except:
print("Something went wrong")
else:
print("Nothing went wrong")
The Finally Clause
• The try except block has an optional finally clause.
• The finally clause is always executed, whether an exception has occurred or not
The Finally Clause
• We can define as many except blocks as we want to catch and handle
specific exceptions.
Example:
try: OUTPUT:
x = 1/0
except: Something went wrong
print("Something went wrong") Always executes this
finally:
print("Always executes this")
Example:
try: OUTPUT:
f=open('text1.txt')
print(f.read()) Something went wrong
except: Always executes this
print("Something went wrong")
finally:
f.close()
Raising an Exception
• If we want to raise an exception when a certain condition occurs, use raise
keyword.
• You can define what kind of error to raise, and the text to print to the user.