0% found this document useful (0 votes)
9 views11 pages

L-5 Exception Handling

Uploaded by

omvati343
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

L-5 Exception Handling

Uploaded by

omvati343
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Session-5

Exception Handling
in Python

Trainer: Ms. Nidhi Grover Raheja

1
Session Overview

Exceptions in Python

Types of Exceptions

Exception Handling Demo

Raise an Exception in Python

Exercise

2
Exceptions in Python
What are Exceptions?

❖An exception is an event, which occurs during the execution of a program and
interrupts its usual flow.

❖An exception is a Python object that represents an error situation.

❖When an exception is raised, it must be handled to prevent the undesired


termination of a program.

❖When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.

❖These exceptions can be handled using the try statement. Since the try block
raises an error, the except block will be executed.
3
Exception Handling Building Blocks
Understanding Exception Handling mechanism

❖The following Exception Handling blocks can be used:

❑The try block lets you test a block of code for errors.

❑The except block lets you handle the error.

❑You can use the else keyword to define a block of code to be executed if no errors were raised

❑The finally block lets you execute code, regardless of the result of the try- and except blocks.

Syntax: Here is simple syntax of try....except...else blocks −


try:
Lines of code that may raise an Exception
except Exception1:
If Exception1 occurs, execute this block of code.
except Exception2:
If Exception2 occurs, execute this block of code.
else:
If no exception occurs, execute this block of code.
4
Exceptions in Python
Types of Exceptions

Exception Name Description


Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisonError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.

5
Exceptions in Python (contd.)
Types of Exceptions

Exception Name Description


ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
IndexError Raised when an index is not found in a sequence.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no
value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
SyntaxError Raised when there is an error in Python syntax.
TypeError Raised when an operation or function is attempted that is invalid for the
specified data type.
ValueError Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
6
Exception Handling
Exception Handling mechanism Demo

❖Example:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("The 'try except' is finished")

7
Raise an exception
How to raise an Exception?

❖We can choose to throw an exception if a condition occurs. To throw (or raise) an
exception, use the raise keyword.

❖The raise keyword is used to raise an exception.

❖Example 1:
#Raise an Error if x is negative:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")

❖Example 2:

• #Raise a TypeError if x is not an integer:


• x = “python“
• if not type(x) is int:
raise TypeError("Only numbers are allowed") 8
User Defined Exceptions
How to create our own Exceptions?

❖ Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions. This is useful when you need to display more specific information when an exception is
caught.

❖ In the try block, the user-defined exception is raised and caught in the except block.

Example:
class OddNumbererror(RuntimeError):
def __init__(self, arg):
self.args = arg

try:
num=int(input("Enter only an even number"))
if(num%2==0):
print(num, " is a Valid even number")
else:
print("Num is odd number")
raise OddNumbererror("Odd Number Error")
except OddNumbererror as e:
9
print ("Odd Number Entered: ",num)
User Defined Exceptions
How to create our own Exceptions?

❖ Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions. This is useful when you need to display more specific information when an exception is
caught.

❖ In the try block, the user-defined exception is raised and caught in the except block.

Example:
class OddNumbererror(RuntimeError):
def __init__(self, arg):
self.args = arg

try:
num=int(input("Enter only an even number"))
if(num%2==0):
print(num, " is a Valid even number")
else:
print("Num is odd number")
raise OddNumbererror("Odd Number Error")
except OddNumbererror as e:
10
print ("Odd Number Entered: ",num)
Exercise 17
Time for Action.

❖Write a program to divide 2 numbers a and b such that a/b. Write


code to handle ZeroDivisonError in the case where user enters zero
(0) value for b.

❖Write a voters eligibility checking program where user is required to


enter his age. If age is 0 or <0 i.e. negative or is >100 then the
program must raise exceptions.

11

You might also like