13539_253_125_Python_Exception_Handling_M3
13539_253_125_Python_Exception_Handling_M3
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.")
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 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.
Code
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
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
Code
Output:
User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets
us design our customized exceptions.
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
Output:
2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):