Introduction
An exception is a class in Python that represents an error; when a Python program gets an error, it stops the execution of the rest of the program. It can be either a syntax error or a Python exception. An exception is an event which occurs during the execution of a program that disrupts the normal flow of the program's instructions.
So Whenever there is an error in a program, exceptions are raised. So when a Python code throws an exception, It has to handle the exception immediately. Otherwise, the program will stop and quit. Python provides many types of exceptions thrown in various situations. Some common exceptions are described below.
Exception Name |
Description |
Exception |
All exceptions inherit this class as the base class for all exceptions. |
ArithmeticError |
Errors that occur during numeric calculation are inherited by it. |
ZeroDivisionError |
Raised when division or modulo by zero takes place. |
ImportError |
Raised when an import statement fails |
NameError |
Raised when an identifier is not found in the local or non-local, or global scope. |
SyntaxError |
Raised when there is an error in Python syntax. |
IndentationError |
Raised when indentation is not proper |
TypeError |
Raised when a specific operation of a function is triggered for an invalid data type |
ValueError |
Raised when invalid values are provided |
RuntimeError |
RuntimeError |
In this example, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. So Python interpreter raises a ZeroDivisionError to indicate that the division is invalid. This error is part of Python's error-handling mechanism and helps prevent unexpected and erroneous calculations.
Syntax
#Python program to raise exception
x = 5
y = 0
z = x/y
print(z)
Output
In Python, exception handling is managed by the following 5 keywords.
- try
- except
- else
- finally
- raise
try
The try block is used to enclose the code that may potentially raise an exception. It is followed by one or more except blocks or an optional else block. The code within the try block is executed, and if any exception occurs, it is caught by the appropriate except block.
Syntax
try:
# statements
except
The except block is used to catch specific exceptions that may occur within the try block. It allows you to specify the type of exception to catch and handle. If an exception of that type (or a subclass of that type) is raised, the corresponding except block is executed. You can have multiple except blocks to handle different types of exceptions.
Syntax
try:
# statements
except:
# statements
else
The else block is optional and follows the except block(s). It is executed if no exceptions occur in the try block. This block is useful when you want to perform additional actions when no exceptions are raised. For example, you can put code in the else block that should only execute if the try block succeeds.
Syntax
try:
# statements
except:
# statements
else:
# statements
finally
The finally block is optional and follows the except or else block(s). It is always executed, regardless of whether an exception occurred or not. The code within the finally block is executed as a cleanup mechanism, allowing you to release resources or perform necessary actions that should always occur, such as closing files or database connections.
Syntax
try:
# statements
except:
# statements
finally:
# statements
raise
The raise keyword is used to explicitly raise an exception. You can use it to throw a specific exception at any point in your code. By raising an exception, you can indicate that an error or exceptional condition has occurred and interrupt the normal flow of execution. You can specify the type of exception to raise and provide an optional error message.
Syntax
try:
raise {name_of_the_exception_class}:
except:
# statements
try-except
The try-except statement in Python is used for exception handling. It allows you to write code that may raise exceptions and handle those exceptions gracefully. Here's a more detailed explanation of the try-except statement. The code that might raise an exception is enclosed within the try block. If an exception occurs within this block, it is immediately caught and processed. The except clause can be used with different types of exceptions, including built-in exceptions like ZeroDivisionError, ValueError, or FileNotFoundError, as well as custom exceptions you define in your code. You can have multiple except
blocks to handle different types of exceptions.
Example
# Python code to illustrate working of try-except
try:
x=10
y=0
result = x // y # Floor Division : Gives only fractional part as answer
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! Cannot divide by zero")
Output
try-except-else
The code that might raise an exception is enclosed within the try block. If an exception occurs within this block, it is immediately caught and processed. If an exception occurs, Python compares the raised exception with each except block in order, from top to bottom. The first except block that matches the raised exception's type (or a subclass of it) is executed. You can have multiple except blocks to handle different types of exceptions. If no exception occurs within the try block, the else block is executed. This block is optional and contains code that should only run if no exceptions were raised. In this example, the user will enter two integers. If the user enters anything other than an integer, a ValueError will be raised and caught by the first except block. If the user enters zero as the second number, a ZeroDivisionError will be raised and caught by the second except block. Otherwise, if both numbers are valid, the division is performed, and the result is printed in the else block. else block is only executed if no exceptions are raised in the try block.
Example
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
except ValueError:
print("Please enter integers only.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("The result of the division is:", result)
Output
try-except-finally
The try-except-finally statement in Python is used for exception handling along with a final cleanup process. It allows you to catch and handle exceptions while ensuring that certain code is executed regardless of whether an exception occurred or not. It is always executed, regardless of whether an exception occurred or not. The code within the finally block is typically used for cleanup operations that must be performed, such as releasing resources, closing files, or restoring the program's state.
In this example, we are trying to open a file called "example.txt" and read its contents. If the file does not exist, a FileNotFoundError will be raised and caught by the first except block. If any other type of exception occurs, it will be caught by the second except block. Finally, the file is closed in the finally block to ensure that the file is always closed; it will always execute whether an exception occurred or not.
Example
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
except:
print("An error occurred.")
finally:
file.close()
print("File closed.")
raise keyword
The raise keyword in Python is used to explicitly raise an exception. It allows you to interrupt the normal flow of execution and indicate that an error or exceptional condition has occurred. Here's a more detailed explanation of the raise keyword. You specify the type of exception you want to raise after the raise keyword. This can be a built-in exception like ValueError, TypeError, or CustomException (a custom exception you define), or it can be an instance of an exception. When the raise statement is executed, it immediately raises the specified exception. The program flow is interrupted, and the exception starts propagating up the call stack to find an appropriate exception handler.
Example
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative")
else:
print("your age is: ",age)
Output
Conclusion
In this article, we have discussed Python's exception handling mechanism using the try, except, and finally blocks. Python's exception handling mechanism using the try, except, and finally blocks is powerful for managing errors and unexpected situations in your code. By enclosing code that may raise exceptions within a try block and providing corresponding except blocks to handle specific exceptions, you can ensure that your program handles errors gracefully and continues execution instead of crashing. It is an essential feature in any programming language to handle errors and unexpected situations.