0% found this document useful (0 votes)
254 views

Exception Handling

The document discusses exception handling in Python, explaining that exceptions represent errors that occur during program execution and disrupt normal flow, and that Python provides try and except blocks to handle exceptions gracefully rather than causing program crashes; it also covers built-in exceptions, raising custom exceptions, and using else and finally clauses with try/except statements.

Uploaded by

naitik S T
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
254 views

Exception Handling

The document discusses exception handling in Python, explaining that exceptions represent errors that occur during program execution and disrupt normal flow, and that Python provides try and except blocks to handle exceptions gracefully rather than causing program crashes; it also covers built-in exceptions, raising custom exceptions, and using else and finally clauses with try/except statements.

Uploaded by

naitik S T
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Exception Handling

Introduction
 A Python program terminates as soon as it
encounters an error.
 In Python, an error can be a syntax error or an
exception.
 Syntax errors occur when the parser detects an
incorrect statement.
Example of Syntax error
 Print( 0 / 0 ))
 File "<stdin>", line 1
 Print( 0 / 0 ))
 ^
 SyntaxError: invalid syntax
 Syntax error is represented with ^ mark. Remove the
extra brace ‘)’
Exception
 An exception is an event, which occurs during the
execution of a program that disrupts the normal
flow of the program's instructions.
 An exception is a Python object that represents an
error.
 When a Python script raises an exception, it must
either handle the exception immediately otherwise
it terminates and quits.
Exception

 When an exception occurs, the python interpreter


 stops the current process and

passes it to the calling process.

If not handled, the program will crash.
Exception
 Ex: For example, let us consider a program where
we have a function A that calls function B, which
in turn calls function C. If an exception occurs in
function C but is not handled in C, the exception
passes to B and then to A.
 If never handled, an error message is displayed and
program comes to a sudden unexpected halt.
Exception
 An exception occurs when syntactically correct
Python code results in an error.
 Example:
 >>> print( 0 / 0)
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 ZeroDivisionError: integer division or modulo by
zero
List of Standard Exceptions
 ZeroDivisionError: Occurs when a number is divided by
zero.
 NameError: It occurs when a name is not found. It may be
local or global.
 IndentationError: If incorrect indentation is given.
 IOError: It occurs when Input Output operation fails.
 EOFError: It occurs when the end of the file is reached,
and yet operations are being performed.
List of Standard Exceptions
 Import Error: Raised when import statement fails.
 Index Error: Raised when index is not found.
 Key Error: Raised when specific key is not found in the
dictionary.
 Name Error: Raised when identifier is not found.
 IOError: Raised when I/O operations fail.
Why to handle Exceptions?
 Exception handling allows you to separate error-handling
code from normal code.
 It clarifies the code and enhances readability.

An exception is a convenient method for handling error
messages.
 An exception can be raised in the program by using the
raise exception method.
Catching exceptions in Python
 In python, exceptions can be handled using try
statement.
 The operation which can raise an exception is
placed inside the try clause.
 The code that handles the exceptions is written in
the except clause.
Catching exceptions in Python
Catching Specific Exceptions in Python
Raising Exceptions in Python
manually raise exceptions using the raise keyword.

>>> raise KeyboardInterrupt

try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
Python try with else clause
Python try with else clause
Python try with else

try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c=a/b
print("a/b = %d" % c)

except ZeroDivisionError:
print("Can't divide by zero")
else:
print("We are in else block ")
Python try with else

try:
# block of code
except Exception1:
# block of code
else:
# this code executes when exceptions not occured
Python try with else and finally clause

try:
a = 10
b=0
c = a/b
print("The answer of a divide by b:", c)
except:
print("Can't divide with zero. Provide different number")
Python try with else and finally clause
try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c = a/b
print("The answer of a divide by b:", c)
except ValueError:
print("Entered value is wrong")
except ZeroDivisionError:
print("Can't divide by zero")
Python try with else and finally clause
Python try with else and finally clause
Python try with else and finally clause

try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
# after the try and any except block
Python try with else and finally clause

try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c=a/b
print("The answer of a divide by b:", c)

except ZeroDivisionError:
print("Can't divide with zero")
finally:
print("Inside a finally block")
Handling Multiple Exceptions
Often code in try suite can throw more than one type
of exception
Need to write except clause for each type of exception
that needs to be handled
An except clause that does not list a specific
exception will handle any exception that is raised in
the try suite
Should always be last in a series of except clauses
Try
suite
Except(exception1[,exception2[,….exception N]]]):
exception_suite
Else:
else_suite
Try:
a=int(input(“first number”)
b=int(input(“second number”)
result= a/b
print(result)
Except(zerodivisionerror,typeerror):
print(“error occurred”)
Else:
print(“successful Division”)
Displaying an Exception’s
Default Error Message
Exception object: object created in memory when an
exception is thrown
Usually contains default error message pertaining to the
exception
Can assign the exception object to a variable in an
except clause
Example: except ValueError as err:
Can pass exception object variable to print function to
display the default error message
The else Clause
try/except statement may include an optional
else clause, which appears after all the except
clauses
Aligned with try and except clauses
Syntax similar to else clause in decision structure
Else suite: block of statements executed after statements
in try suite, only if no exceptions were raised
If exception was raised, the else suite is skipped
The finally Clause
try/except statement may include an optional
finally clause, which appears after all the except
clauses
Aligned with try and except clauses
General format: finally:
statements
Finally suite: block of statements after the finally clause
Execute whether an exception occurs or not
Purpose is to perform cleanup before exiting
What If an Exception Is Not
Handled?
Two ways for exception to go unhandled:
No except clause specifying exception of the right type
Exception raised outside a try suite
In both cases, exception will cause the program to
halt
Python documentation provides information about
exceptions that can be raised by different functions
Raising an Exceptions
def simple_interest(amount, year, rate):
try:
if rate > 100:
raise ValueError(rate)
interest = (amount * year * rate) / 100
print('The Simple Interest is', interest)
return interest
except ValueError:
print('interest rate is out of range', rate)
print('Case 1')
simple_interest(800, 6, 8)

print('Case 2')
simple_interest(800, 6, 800)
Custom and User-defined Exceptions

class Error(Exception):
"""Base class for other exceptions"""
pass

class ValueTooSmallError(Error):
"""Raised when the input value is small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is large"""
pass
Custom and User-defined Exceptions
while(True):
try:
num = int(input("Enter any value in 10 to 50 range: "))
if num < 10:
raise ValueTooSmallError
elif num > 50:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("Value is below range..try again")

except ValueTooLargeError:
print("value out of range...try again")

print("Great! value in correct range.")


Custom and User-defined Exceptions
class NegativeAgeError(Exception):

def __init__(self, age, ):


message = "Age should not be negative"
self.age = age
self.message = message

age = int(input("Enter age: "))


if age < 0:
raise NegativeAgeError(age)
# Output:
# raise NegativeAgeError(age)
# __main__.NegativeAgeError: -9

You might also like