Exception Handling
In Python, an exception is an error that occurs during the execution of a
program. When an exception occurs, Python stops the normal flow of
execution and jumps to the nearest exception handler. If no exception
handler is found, the program terminates and prints an error message.
Exception Handling Steps:
- Use a try block to enclose the code that might raise an exception.
- Use one or more except blocks to handle the specific exception(s) that might be raised.
- Optionally, use finally block to execute code that should be run whether or not an exception was raised .
- Optionally, raise a new exception using the raise keyword if the situation warrants it.
Syntax:
try:
# Code that might raise an exception
...
except ExceptionType1:
# Code to handle ExceptionType1
...
except ExceptionType2:
# Code to handle ExceptionType2
...
except:
# Code to handle all other exceptions
...
finally:
# Code to be executed regardless of whether an exception was raised
or
not
Program:
try: num1 =
int(input("Enter a number: ")) num2 =
int(input("Enter another number: ")) result =
num1 / num2 print("The result is:", result) except
ValueError:
print("Please enter a valid integer:") except ZeroDivisionError:
print("Cannot divide by zero.") except Exception as e:
print("An error occurred:", e)
finally:
print("Program completed.")
Output:
#ZeroDivisionError
Enter a number: 10 Enter another number: 0
Cannot divide by zero. Program completed.
#Value error
Enter a number: abc
Please enter a valid integer. Program completed.
#correct output
Enter a number: 10 Enter another number: 2
The result is: 5.0 Program completed.
More topic in Python