Exception handling in python

1. An exception is an error that happened during the execution of program.

2. The python programming provides the exception handling during the execution of the                   program.

3.  This exception are handled by using try,except and final statements.

Try and except statement

1. This statement are used to catch and handle exceptions in python.

2. The handle exception are written inside except block.

Syntax of try and except statement

Try:
 {Body}
Except Indexerror:
 {Body}
Except valueerror:
 {Body}

Finally keyword in python

1. Python provides a keyword Finally, which is always executed after the try and except blocks.

Syntax
Try:
 {Body}
Except:
 {Body}
Finally:
 {Body}
#always executed
Example program
try:
    # Trying to divide by zero
    result = 10 / 0
    print("The result is:", result)
except ZeroDivisionError:
    # Handling division by zero
    print("Error: Cannot divide by zero.")
finally:
    # This block will always execute
    print("This block is executed no matter what.")
Output of program
Error: Cannot divide by zero. 
This block is executed no matter what.

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top