Exception Handling
Exception Handling
What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.
Exception Handling
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code that handles the exception
Examples
except Statement with No Exception Type
In Python, the except statement can be used without specifying any exception type. This
allows it to catch all exceptions, regardless of their type.
Example
try:
num = int(input("Enter a number: ")) # Code that may cause an exception
result = 10 / num
except:
print("An error occurred. Something went wrong.")
Common Exceptions
6. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
7. FileNotFoundError: Raised when trying to open a file that does not exist.
try...finally Block
In Python, the try...finally block provides a structured way to handle errors (exceptions) and
ensure some code always runs.
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to run if there is no exception
finally:
# Code that runs no matter what
1. try:
This block contains code that might raise an exception (error).
2. except:
This block runs only if an exception occurs in the try block.
3. else:
This block runs only if no exception occurs in the try block.
4. finally:
This block runs no matter what happens, whether an exception occurs or not.
Example
try:
num = int(input("Enter a number: ")) # Code that may cause an exception
result = 10 / num
else:
# Runs only if no exception occurs
print("Success! Result =”, result)
finally:
# Always runs
print("Execution completed.")
Raise
You want to stop a function or program if a specific condition is met. You can raise an
exception to inform the user or stop execution.
Example
Output: