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

13539_253_125_Python_Exception_Handling_M3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

13539_253_125_Python_Exception_Handling_M3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Exception Handling

What is an Exception in Python?


An exception is an error which happens at the time of execution of
a program. However, while running a program, Python generates
an exception that should be handled to avoid your program to
crash. In Python language, exceptions trigger automatically on
errors, or they can be triggered and intercepted by your code.

Common Examples of Exception


❑ Division by Zero
❑ Accessing a file which does not exist.
❑ Addition of two incompatible types
❑ Trying to access a nonexistent index of a
sequence
❑ Removing the table from the
disconnected database server.
❑ ATM withdrawal of more than the
available amount
Exceptional Handling Mechanism
Exception handling is managed by the
following 4 keywords:
1. try
2. catch
3. finally
4. throw
The try Statement: A try statement includes keyword try, followed by a colon (:) and a suite of
code in which exceptions may occur. It has one or more clauses. During the execution of the try
statement, if no exceptions occurred then, the interpreter ignores the exception handlers for that
specific try statement.

Python try...except Block


The try...except block is used to handle exceptions in Python. Here's the
syntax of try...except block:

try:
# code that may cause exception
except:
# code to run when exception occurs

Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by an except block.
When an exception occurs, it is caught by the except block.
The except block cannot be used without the try block.
Example: Exception Handling Using try...except
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.

In the example, we are trying to divide a number by 0. Here, this code


generates an exception.
To handle the exception, we have put the code, result =

numerator/denominator inside the try block. Now when an exception


occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside
the except block are executed.

In Python, we catch exceptions and handle them using try and except
code blocks. The try clause contains the code that can raise an exception,
while the except clause contains the code lines that handle the exception.
Let's see if we can access the index from the array, which is more than
the array's length, and handle the resulting exception.

Code

1. # Python code to catch an exception and handle it using try and except code blo
cks
2. a = ["Python", "Exceptions", "try and except"]
3. try:
4. #looping through the elements of the array a, choosing a range that goes bey
ond the length of the array
5. for i in range( 4 ):
6. print( "The index and element from the array is", i, a[i] )
7. #if an error occurs in the try block, then except block will be executed by the Pyt
hon interpreter
8. except:
9. print ("Index out of range")

Output:

The index and element from the array is 0 Python


The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range

The code blocks that potentially produce an error are inserted inside the
try clause in the preceding example. The value of i greater than 2
attempts to access the list's item beyond its length, which is not present,
resulting in an exception. The except clause then catches this exception
and executes code without stopping it.

How to Raise an Exception


If a condition does not meet our criteria but is correct according to the
Python interpreter, we can intentionally raise an exception using the raise
keyword. We can use a customized exception in conjunction with the
statement.

If we wish to use raise to generate an exception when a given condition


happens, we may do so as follows:

Code

1. #Python code to show how to raise an exception in Python


2. num = [3, 4, 5, 7]
3. if len(num) > 3:
4. raise Exception( f"Length of the given list must be less than or equal to 3 but i
s {len(num)}" )

Output:

1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than
or equal to 3 but is {len(num)}" )

Exception: Length of the given list must be less than or equal to 3 but is
4

The implementation stops and shows our exception in the output,


providing indications as to what went incorrect.

Try with Else Clause


Python also supports the else clause, which should come after every
except clause, in the try, and except blocks. Only when the try clause fails
to throw an exception the Python interpreter goes on to the else block.

Here is an instance of a try clause with an else clause.

Code

1. # Python program to show how to use else clause with try and except clau
ses
2.
3. # Defining a function which returns reciprocal of a number
4. def reciprocal( num1 ):
5. try:
6. reci = 1 / num1
7. except ZeroDivisionError:
8. print( "We cannot divide by zero" )
9. else:
10. print ( reci )
11. # Calling the function and passing values
12. reciprocal( 4 )
13. reciprocal( 0 )

Output:

0.25
We cannot divide by zero

Finally Keyword in Python


The finally keyword is available in Python, and it is always used after the
try-except block. The finally code block is always executed after the try
block has terminated normally or after the try block has terminated for
some other reason.

Here is an example of finally keyword with try-except clauses:

Code

1. # Python code to show the use of finally clause


2.
3. # Raising an exception in try block
4. try:
5. div = 4 // 0
6. print( div )
7. # this block will handle the exception raised
8. except ZeroDivisionError:
9. print( "Atepting to divide by zero" )
10. # this will always be executed no matter exception is raised or not
11. finally:
12. print( 'This is code of finally clause' )

Output:

Atepting to divide by zero


This is code of finally clause

User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets
us design our customized exceptions.

Here is an illustration of a RuntimeError. In this case, a class that derives


from RuntimeError is produced. Once an exception is detected, we can
use this to display additional detailed information.

We raise a user-defined exception in the try block and then handle the
exception in the except block. An example of the class EmptyError is
created using the variable var.

Code

1. class EmptyError( RuntimeError ):


2. def __init__(self, argument):
3. self.arguments = argument
4. Once the preceding class has been created, the following is how to raise
an exception:
5. Code
6. var = " "
7. try:
8. raise EmptyError( "The variable is empty" )
9. except (EmptyError, var):
10. print( var.arguments )

Output:

2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):

EmptyError: The variable is empty

You might also like