0% found this document useful (0 votes)
2 views19 pages

Exception Handling in Python

The document explains exception handling in Python, detailing what exceptions are and how to manage them using try, except, and finally blocks. It provides examples of handling specific exceptions like ZeroDivisionError and demonstrates the use of the raise statement to throw exceptions. Key points include the necessity of using except or finally with try blocks and the importance of handling multiple exceptions correctly.

Uploaded by

jyotsnakumari931
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)
2 views19 pages

Exception Handling in Python

The document explains exception handling in Python, detailing what exceptions are and how to manage them using try, except, and finally blocks. It provides examples of handling specific exceptions like ZeroDivisionError and demonstrates the use of the raise statement to throw exceptions. Key points include the necessity of using except or finally with try blocks and the importance of handling multiple exceptions correctly.

Uploaded by

jyotsnakumari931
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/ 19

Exception Handling in Python

“Handling the runtime errors”


What are Exceptions?
• an exception is an event that occurs during
the execution of a program that disrupts the
normal flow of instructions.
• These exceptions can occur for various
reasons, such as invalid user input, file not
found, or division by zero.
Handling Exceptions
• It is a powerful mechanism to handle the
runtime errors so that the normal flow of
application can be maintained.
• Since exception abnormally terminate the
execution of a program, it is important to
handle the exceptions. In Python we use try
and except block to handle the exception.
Another keyword finally can also be used to
perform cleanup task.
try block
• try block lets you test a block of code for
errors.
• We put all those codes inside the try block
which may raise runtime errors.
• When try block encounters any runtime error
the control is passed to appropriate except
block.
except block
• Except block lets you handle runtime errors
• When any runtime error occurs in try block
the control is transferred to except block to
handle and maintain the normal execution of
program
• Default “except” block can handle any type of
runtime errors however we can pass the name
of runtime error with except block to handle
specific type of runtime error.
Example – 1 (Handling Divide by Zero)

When we input
valid data, program
will execute
successfully

If denominator is
entered as 0, then
program will crash
with runtime error
“ZeroDivisionError”
Example – 2 (Handling Divide by Zero)

When we input
valid data, program
will execute
successfully

If denominator is entered
as 0, then program will
not abnormally terminate
and error is handled
gracefully

,
Example – 2 (Handling Divide by Zero)

However, here we used except


block which can handle any type
of runtime errors, so if try block
raises any other runtime error like
ValueError when we input invalid
data in variable a or b like string,
the same message ‘Sorry you
cannot divide by zero’ will be
printed
,
Example – 3 (Handling specific Exception)

Name of specific
exception is given

Successful execution with valid data

Divide by 0 error is handled successfully

,
Example – 3 (Handling specific Exception)

As only ZeroDivisionError exception is handle here, if any other runtime error occurs like if
we input string data in place of Int data, then program wi llc rash with ValueError Exception
Example – 4 (Multiple Exception Handling)
Example – 4 (Multiple Exception Handling)

Executed successfully

Divide by Zero Case

If wrong input supplied

Occurs because variable d is not defined and


assigned, NameError Exception will occur
and will be handled by except block

,
finally block
• The 'finally' block of python is always executed
whether an exception in code occurred or
not.
• It allows us to perform clean-up actions like
releasing resources or closing files,
irrespective of the presence of exceptions.

,
Example (with finally block)

Here we can see


that code of finally
block executed in
both cases, whether
exception occurred
on not
,
Points to remember
• try block must be followed by either except or
finally block
• except block is not mandatory with try block, we
can write either except or finally. However to
handle error for successful execution of program
except block is must.
• While handling multiple exception the except
block must be the last block otherwise all other
exception given below except will become
unreachable. Syntax error will appear with
message ‘default except must be last’
Raising Exceptions

 The python interpreter raise( throws) an exception.


 Exception Handlers are designed to execute when a specific
exceptions are raised.
 We can also forcefully raise exceptions using raise and assert
statement.
 Raising an exception will interrupt the normal flow of
execution.
 It jumps to the exception handler code.
The raise Statement

 The raise statement can be used to raise(throws) an


exception.
Syntax: raise exception-name[(optional argument)]
Example: raise Exception(“OOPS!! An Exception has
occurred”)

[The error may be built-in exception or user-defined]

Example: Built-in Exception(IndexError)

numbers=[20,30,40,50]
length=10
if length>len(numbers):
raise IndexError
print("No execution")
else:
print(length)

Output:
Traceback (most recent call last):
File "C:\Users\Rithika\OneDrive\Desktop\sample
python\Excep.py", line 17, in <module>
raise IndexError
IndexError

Explanation:
1. The value of variable length is greater than the length of the
list numbers. (IndexError exception will be raised)
2. The statement following the raise statement will not be
executed.
3. The message “NO EXECUTION” will not be displayed in this
case.

When to use Raise?


Use **raise**when you want to handle or report errors in your
code.

You might also like