Exception Handling PDF
Exception Handling PDF
Exceptions in Python
When writing a program, we may encounter errors.
An error is called as syntax error or parsing error if the syntax
of a language is not followed.
Errors can also occur at runtime and these are called
Exceptions.
They occur
1. When we try to open a file which does not exist
(FileNotFoundError),
2. Dividing a number by zero (ZeroDivisionError),
3. Module we try to import is not found (ImportError) etc.
Whenever these type of runtime errors 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.
What are exceptions in Python
There are various built-in exceptions in Python that are
raised when corresponding errors occur.
Some of the common built-in exceptions in Python
programming along with the error that cause then are
tabulated below.
For example, if function A calls function B which in turn
calls function C and an exception occurs in function C. If
it is not handled in C, the exception passes to B and then
to A.
If never handled, an error message is spit out and our
program come to a sudden, unexpected halt.
Python Built-in Exceptions
Exception Cause of Error
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
Raised when result of an arithmetic operation is too large to
OverflowError
be represented.
Raised when a weak reference proxy is used to access a
ReferenceError
garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
Continued…..
Exception Cause of Error
a=3
b=0
c = a/b
print('Hello')
Output:
ZeroDivisionError: division by zero
Continued…..
Once the error occurs, none of the code after c=a/b
will get executed.
The program will just stop running and probably
close.
When an error occurs, an exception is generated.
You can catch this exception and allow your program
to recover from the error without crashing.
Catching Exceptions in Python
In Python, exceptions can be caught using a try statement.
A critical operation which can raise exception is placed inside
the try clause and the code that handles exception is written
in except clause.
It is up to us, what operations we perform once we have
caught the exception.
Syntax:
try:
some statements here
except:
exception handling
Output:
Error
Hello
Catching Specific Exceptions in Python
In the above example, we did not mention any exception
in the except clause.
This is not a good programming practice as it will catch
all exceptions and handle every case in the same way.
We can specify which exceptions an except clause will
catch.
Example
try:
print (1/0)
except ZeroDivisionError:
print ("You can't divide by zero")
Output:
You can't divide by zero
try:
some statements here
Except (exception1, exception2,exception3):
exception handling
Example
try:
a = int(input('Enter a number: '))
print (3/a)
except (ValueError, ZeroDivisionError):
print('Something went wrong')
Output:
Enter a number: d
Something went wrong
Enter a number: 0
Something went wrong
exception ArithmeticError
This class is the base class for those built-in exceptions
that are raised for various arithmetic errors such as
1. OverflowError
2. ZeroDivisionError
3. FloatingPointError
try…. else
try:
a = 10/0
print (a)
except ArithmeticError:
print ("Arithmetic exception raised." )
else:
print ("Success.")
Output:
Arithmetic exception raised
try….finally
You can use a finally: block along with a try: block.
Finally block consists of the finally keyword.
It is placed after the last except block.
It is intended to define clean-up actions that must be executed under all
circumstances.
If an exception is thrown, the finally block will execute even if no except
statement matches that exception.
Syntax:
try:
You do your operations here; ......................
except :
Handle exception
finally:
This would always be executed. ......................
Example
a=3
b=0
try:
print(a/b)
except ZeroDivisionError:
print("Something went wrong")
finally:
print("Printed finally")
Output:
Something went wrong
Printed finally
Raising Exception:
The raise statement can be used by the programmers to
raise their own exceptions.
User-triggered exceptions are caught the same way as
they are raised by Python.
This is useful if you are writing your own classes to be
used in other programs and you want to send messages,
like error messages, to people who are using your class.
The only argument in raise indicates the exception to be
raised.
Syntax:
x = 10
try:
if x > 5:
raise Exception
except Exception:
print('X should not exceed 5')
Output:
Traceback (most recent call last):
File "<input>", line 4, in <module>
Exception: x should not exceed 5
The program comes to a halt and displays our exception to screen, offering
clues about what went wrong.
The AssertionError Exception
Instead of waiting for a program to crash midway, you can also
start by making an assertion in Python.
We assert that a certain condition is met.
If this condition turns out to be True, then that is excellent!
The program can continue.
If the condition turns out to be False, you can have the
program throw an AssertionError exception.
Example
import sys
assert ('linux' in sys.platform), “Code runs on Linux only.”
try:
num = int(input("Enter your age: "))
enterage(num)
except ValueError:
print("Only positive integers are allowed")
Find Output
try:
with open('new.txt') as file:
read_data = file.read()
print(read_data)
except:
print('Could not open file.log')
Find Output
try:
a=3
if a < 4:
b = a / (a - 3)
print("Value of b = ", b)
except(ZeroDivisionError, NameError):
print("Error Occurred and Handled")