Home » Posts tagged 'Python exception handling best practices'
Tag Archives: Python exception handling best practices
Build-in exception in python
When certain faults or extraordinary circumstances arise during the execution of a programme, built-in exceptions in the Python programming language can be raised (or thrown). These exceptions, which are defined in the Python standard library, can be applied to deal with particular error kinds.
1.TypeError
: Raised when an operation or function is applied to an object of inappropriate type.
# Example: TypeError
x = 10
y = '5'
z = x + y # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'
2. ValueError
: Raised when a function receives an argument of the correct type but an inappropriate value.
# Example: ValueError
age = input("Enter your age: ")
age = int(age) # Raises ValueError if the input cannot be converted to an integer
3. IndexError
: Raised when a sequence subscript is out of range.
# Example: IndexError
numbers = [1, 2, 3]
print(numbers[3]) # Raises IndexError: list index out of range
4. KeyError
: Raised when a dictionary key is not found.
# Example: KeyError
person = {'name': 'John', 'age': 30}
print(person['gender']) # Raises KeyError: 'gender'
5. FileNotFoundError
: Raised when a file or directory is requested but cannot be found.
# Example: FileNotFoundError
file_path = 'path/to/nonexistent/file.txt'
with open(file_path, 'r') as file: # Raises FileNotFoundError
content = file.read()
6. ZeroDivisionError
: Raised when division or modulo operation is performed with zero as the divisor.
# Example: ZeroDivisionError
x = 10
y = 0
result = x / y # Raises ZeroDivisionError: division by zero
7. ZeroDivisionError
: Raised when division or modulo operation is performed with zero as the divisor.
8. ImportError
: Raised when an import statement fails to find and load a module.
9. AssertionError
: Raised when an assert statement fails.
10. StopIteration
: Raised to signal the end of an iterator.
These are just a few examples of built-in exceptions in Python. You can also create your own custom exceptions by deriving from the base Exception
class or any other built-in exception class.
Python Exception Handling
In Python, handling exceptions is a technique for managing any faults or unusual circumstances that may arise while a programme is being executed. It enables you to gracefully handle some errors rather than having the programme end suddenly by allowing you to catch and handle them.
Python provides a built-in mechanism for exception handling using the try-except
statement. The general syntax is as follows:
try:
# Code block where an exception might occur
except ExceptionType1:
# Code to handle the exception of type ExceptionType1
except ExceptionType2:
# Code to handle the exception of type ExceptionType2
...
except:
# Code to handle any other exceptions
else:
# Code to execute if no exception occurs
finally:
# Code that is always executed, regardless of whether an exception occurred or not
Here’s an explanation of the different parts:
- The
try
block contains the code where you anticipate an exception might occur. - The
except
block is used to catch and handle specific types of exceptions. You can have multipleexcept
blocks to handle different types of exceptions. ExceptionType1
,ExceptionType2
, and so on, represent the specific types of exceptions you want to handle. For example,ValueError
,TypeError
, orIOError
.- If an exception occurs in the
try
block and matches the specified exception type, the correspondingexcept
block is executed. If no exception occurs, theexcept
block is skipped. - You can have a generic
except
block without specifying the exception type. It will catch any exception that is not handled by the precedingexcept
blocks. However, it is generally recommended to catch specific exceptions whenever possible. - The
else
block is optional and contains code that will be executed if no exception occurs in thetry
block. - The
finally
block is also optional and contains code that will always be executed, regardless of whether an exception occurred or not. It is typically used for cleanup tasks, such as closing files or releasing resources.
Here’s an example to illustrate how exception handling works:
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Invalid input. Please enter integers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print("An error occurred:", str(e))
else:
print("Division operation completed successfully.")
finally:
print("Exiting the program.")
In this example, if the user enters invalid input (non-integer values), a ValueError is raised and caught by the first except block. If the user enters zero as the denominator, a ZeroDivisionError is raised and caught by the second except block. Any other unhandled exceptions will be caught by the generic except block. The else block is executed if no exception occurs, and the finally block is always executed at the end, regardless of exceptions.
By using exception handling, you can ensure that your program handles errors gracefully, provides meaningful error messages, and continues executing even in the presence of exceptions