Python - Exceptions Handling
In Python, exceptions are raised whenever there is an error during the execution of a program. Python provides a number of built-in exceptions, each designed to handle specific errors. Here are some commonly used built-in exceptions:
- SyntaxError: This exception is raised when there is a syntax error in the code. For example, if you forget to put a colon after a conditional statement or a loop, this error will be raised.
- NameError: This exception is raised when a variable or a function is not defined. For example, if you try to use a variable that has not been defined, this error will be raised.
- TypeError: This exception is raised when you try to perform an operation on a variable or a value of a type that is not supported. For example, if you try to concatenate a string and an integer, this error will be raised.
- IndexError: This exception is raised when you try to access an element of a sequence (such as a list or a tuple) that is out of range.
- KeyError: This exception is raised when you try to access a key in a dictionary that does not exist.
- ValueError: This exception is raised when a function or a method receives an argument of the correct type, but with an inappropriate value.
- ZeroDivisionError: This exception is raised when you try to divide a number by zero.
There are many other built-in exceptions in Python, as well as the ability to create your own custom exceptions.
To handle exceptions in Python, you use the try-except block. The code that could potentially raise an exception goes inside the try block, and the code to handle the exception goes inside the except block.
The syntax of try-except statement is as follows:
try:
# code that may raise an exception
except ExceptionType:
# code to handle the exception
In the above code, the try block contains the code that may raise an exception. If an exception is raised, the code in the except block is executed to handle the exception.
Here's an example of using try-except to handle a division by zero error:
try:
result = 10/0
except ZeroDivisionError:
print("Division by zero error occurred!")
In the above example, we try to divide 10 by 0 which raises a ZeroDivisionError exception. The except block catches this exception and prints a message to the console.
We can also have multiple except blocks to handle different types of exceptions. Here's an example:
try:
num = int(input("Enter a number: "))
result = 10/num
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Division by zero error occurred!")
except:
print("Some other error occurred!")
In the above example, we first take an input from the user and try to divide 10 by the input number. If the input is not a valid number, a ValueError exception is raised. If the input number is 0, a ZeroDivisionError exception is raised. If any other type of exception occurs, the last except block catches it and prints a generic error message.
We can also use the finally block to execute a piece of code regardless of whether an exception was raised or not. The finally block is executed after the try and except blocks. Here's an example:
try:
f = open("file.txt", "r")
# some code to read the file
except FileNotFoundError:
print("File not found!")
finally:
f.close()
In the above example, we try to open a file for reading. If the file is not found, a FileNotFoundError exception is raised. The finally block is used to close the file handle, regardless of whether an exception was raised or not.