Python Error and Exception Handling
Error and Exception handling is a mechanism in Python to handle unexpected errors or exceptions that may occur during the execution of a program. It enables the program to continue running even if an error occurs, instead of terminating abruptly.
In Python, exceptions are raised when an error occurs, and they can be handled using try-except blocks. The try
block contains the code that may raise an exception, and the except
block contains the code that will handle the exception if it occurs.
Here's a basic example of how to use try-except blocks in Python:
try:
x = int(input("Enter a number: "))
print("The number entered is: ", x)
except ValueError:
print("Oops! That was not a valid number. Try again...")
In this example, the try
block attempts to convert the input from the keyboard to an integer using the int
function. If the input is not a valid integer, a ValueError
exception will be raised. The except
block will then catch the exception and display a message to the user.
You can also handle multiple exceptions in a single try-except block, by specifying multiple except
blocks, each handling a different type of exception.
Here's an example:
try:
x = int(input("Enter a number: "))
y = 1 / x
print("The result is: ", y)
except ValueError:
print("Oops! That was not a valid number. Try again...")
except ZeroDivisionError:
print("Oops! Cannot divide by zero. Try again...")
In this example, the try
block attempts to divide 1
by the entered number x
. If x
is not a valid integer, a ValueError
exception will be raised. If x
is zero, a ZeroDivisionError
exception will be raised. Both exceptions are handled in separate except
blocks.
Finally, the finally
block can be used to specify code that will always be executed, regardless of whether an exception occurs or not.
Here's an example:
try:
x = int(input("Enter a number: "))
y = 1 / x
print("The result is: ", y)
except ValueError:
print("Oops! That was not a valid number. Try again...")
except ZeroDivisionError:
print("Oops! Cannot divide by zero. Try again...")
finally:
print("This code will always be executed.")
In this example, the finally
block contains code that will always be executed, regardless of whether an exception occurs or not. This can be used to close files or release resources that need to be cleaned up, for example.
Leave a Comment