0% found this document useful (0 votes)
26 views7 pages

Exception Handling

Rdg

Uploaded by

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

Exception Handling

Rdg

Uploaded by

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

Exceptiona Handling

INTRODUCTION
Python exception handling is a mechanism that allows you to gracefully handle
errors and exceptions that occur during the execution of your code. It helps
prevent your program from crashing and allows you to handle errors in a controlled
manner.
Syntax for Exception Handling
The basic structure of exception The code inside the try block is executed. If an
handling in Python involves exception is raised while executing this code, it
using the is caught by the corresponding except block.
try :
Statement(s) If no exception occws, the code in the else block
except: is executed In this case, it simply prints a
Statement(s) success message. The finally block is always
else: executed, regardless of whether an exception
Statement(s) occurs or not.
finally:
Statement(
s)
Important Point for Exception Handling

(1)A single try statement can have multiple except statements. This
is useful when the try block contains statements that may throw
different types of exceptions.
(2) You can also provide a generic except clause, which handles any
exception.
(3) Aher the except clause(s), you can include an else-clause. The code in
the else-block executes if the code in the try: block does not raise an
exception.
(4) The else-block is a good place for code that does not need the try:
block's protection.
THE EXCEPT CLAUSE WITH MULTIPLE EXCEPTIONS
In Python, you can use a single except clause to catch multiple exceptions by specifying
them within a tuple. This allows you to handle different types of exceptions in the same blocli of
Here's an example:
code.
In the above example, the try block
thy: contains code that may raise three different
# Code that may raise exceptions file = open("inyfile.txt", "r") types of exceptions:
Fi1cNotFoundF.rror if the tile "myfilc.txt" does
number = int(input("Enter a number: ")) not exist.
result = 10 / number ValueError if the user enters a non-numeric
except (FileNotFoundError, ValueError, ZeroDivisionError): value for the input.
# Handling multiple exceptions print("An error occurred.") ZeroIJivisionError if the user enters zero as
the number.
The except clause catches these exceptions
Notc that the exceptions specitied in the except clause should be compatible with specified within a tuple (FileNotFoundError,
the raised exceptions. If an exception occui's that is not listed in the except
clause, it will not be caught, and the program will terminate with an unhandled ValueError. ZeroDivisioiiError).II’any o1“these
exception. exceptions occur, the code inside the except
By using a single except clause with multiple exceptions, you can handle block is executed, w'hich simply prints an
different exceptions in a concise and efficient manner, reducing code error messagc.
duplication and improving readability.
TRY WITH ELSE CLAUSE
In Python, you can also use the else clause on the try-except block which must be present after all
the except clauses. The code enters the else block only if the try clause does not raise an exception.

# Program to depict else clause with try-except


def divide(a , b):

c = ((a*b) / (a-b))
except ZeroDivisionError:
print ("aA result in 0")
else:
print (c)
TRY WITH FINALLY CLAUSE
Python provides a keyword finall , which is always executed after the try and except blocks. The
final blocli always executes a9er the normal temination of the try block or aher the try block
terminates due to some exception.

”"”’ k = 5//0 # raises divide by zero exception.


print(k)
# op-ioral
blo:X
# handles zerodivision exception
except ZeroDivisionError:
print(”Can't divide by
# execute if no rxcepticn
zero”)
fin 11,.” finally:
# Some c ade . (a I: a'. s e xec ut # this block is always executed
ec)
# regardless of exception generation.
print('This is always executed')
Example
Example
try:
# Code that may raise an exception
numl = int(input(”Enter the first number: "))
num2 = int(input(”Enter the second number: ")) Note:
result = numl / num2 The ValueError exception
print("Result:", result)
except ValucError: is
print("Ovalid input. Please enter valid numericif thevalue,
raised and a the
user enters
numbers.")
except ZeroDivisionError: ZeroDivisionError
non- is
print("Cannot divide by zero. Please enter a raised if the user enters zero as
exception
non-zero
divisor.")
the second number.
else:
print("Division performed successfully.")
finally:
l irin t (”P F ogram execution completest)

You might also like