In this comprehensive guide, we will delve into the best practices for Python exception handling. This will also include discussing try/except blocks, try else, and try/except/finally block.
What is Exception Handling in Python?
Exception handling in Python refers to the process of anticipating and handling errors or exceptional events that may occur during the execution of a program.
It allows developers to gracefully handle and recover from errors, ensuring that the program continues to run without abruptly terminating.
a = 7 b = 0 print (a/b)
Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
The system can’t divide the number by zero in this code, so an exception is thrown.
Python Exception Handling Best Practices
When it comes to exception handling in Python, there are several best practices that can help you write robust and maintainable code.
Here are some of the key recommendations:
- Be specific with exceptions.
- Use multiple except blocks.
- Handle exceptions gracefully.
- Avoid silent failures.
- Use the finally block for cleanup.
- Use context managers for resource handling.
- Avoid bare except statements.
- Use custom exception classes.
- Log exceptions for debugging.
- Test exception scenarios.
Python try, except, else, and finally
- Try: This block will check for the error that was expected to happen.
- Except: This block is where you can take care of the mistake.
- Else: If there are no further errors, this block will be executed.
- Finally: Whether an exception is made or not, the finally block is always executed
Try/Except Blocks in Python
If you think your code might throw an exception, put it in a try block.
try: print(x) except: print("An exception occurred.")
An exception occurred.
The except block will be executed because the try block raised an error. If there was no try block, the program would crash and raise an error.
Python Multiple Excepts
There can be multiple except blocks for a single try block.
Let’s look at some examples of how Python handles more than one exception.
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
Variable x is not defined
The interpreter checks the except blocks to see if any of them can handle the exception when it encounters one. In our example, the first statement under the try block resulted in a NameError.
The try block contains code that may cause an error. The except block contains code that will be executed if an error occurs. If an error occurs, the code in the try block after the error will not be executed.
If an appropriate except block or a generic except block is not found, the exception will go unhandled.
Python Multiple Exception in one Except
You can also have one except block handle multiple exceptions by using parentheses.
try: print('50'+20) print(7/0) except (TypeError,ZeroDivisionError): print("Invalid input")
Try/Else in Python
Using the else clause, you can specify a code block to be performed if no errors occur:
Example: try block does not produce an error.
try: print("Python is Fun!") except: print("There's an error") else: print("No error")
Try/Except/Finally Block in Python
You can include a finally clause exception block after the last except block. This code will execute no matter what.
try: print(7/0) except ValueError: print('Value Error is raised') finally: print('Prints the finally block')
Prints the finally block Traceback (most recent call last): File "<stdin>", line 2, in <module> ZeroDivisionError: division by zero
You might need to throw an exception to handle a situation. You can throw an exception by using the raise keyword.
a = -6 if a < 0: raise Exception("Please input absolute values.")
Raise Without a Specified Exception in Python
You can use the raise keyword without specifying an exception, which will cause the original exception to be raised again. This can only be done inside an except block.
try: print('70'+10) except: raise
Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: can only concatenate str (not "int") to str
Raise With an Argument in Python
You can also include an argument with the exception you’re raising, to give additional details about what happened.
raise ValueError("Enter a appropriate value")
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Enter a appropriate value
Python Built-in Exceptions
Below is the list of all the Built-in Exceptions in Python. You can visit the Python official documentation about the Standard Exception if you want more information.
|Exception||Base class for all exceptions|
|StopIteration||Thrown when an iterator’s next() method doesn’t point to any object.|
|SystemExit||The sys.exit() function raises this error.|
|StandardError||Except for StopIteration and SystemExit, this is the base class for all built-in exceptions.|
|ArithmeticError||Base class for all errors that can happen when working with numbers.|
|OverflowError||Raised when a calculation uses more numbers than a numeric type can handle.|
|FloatingPointError||Raised when a calculation with a floating point number fails.|
|ZeroDivisionError||Raised when any type of number is divided by zero or moduloed by zero.|
Raised when the second argument of a division or modulo operation is zero
|AssertionError||If the Assert statement fails, this event is raised.|
|AttributeError||If the reference or assignment of an attribute fails, this event is raised.|
|EOFError||If the reference or assignment of an attribute fails, this event is raised.|
|ImportError||If an import statement fails, this event is thrown.|
|KeyboardInterrupt||When the user stops the program from running, usually by pressing Ctrl+c, this signal is sent.|
|LookupError||Base class for the exceptions that are thrown when a key or index used on a mapping or sequence is not valid.|
|IndexError||Thrown when a sequence can’t find an index.|
|KeyError||Raised when the key does not exist in the dictionary.|
|NameError||Raised when an identifier can’t be found in either the local or global namespace.|
|UnboundLocalError||Raised when a reference tries to use a local variable in a function or method that hasn’t been given a value yet.|
|EnvironmentError||This is the base class for all exceptions that happen outside of Python.|
|IOError||Raised when an input/output operation fails, like when the print statement or the open() function try to open a file that doesn’t exist.|
|SyntaxError||Raised when there is a mistake in the way Python is written.|
|IndentationError||Raised when indentation is not specified properly.|
|SystemError||Raised when the interpreter finds an internal error. However, when this error is thrown, the Python interpreter does not close.|
|SystemExit||When the sys.exit() function is used to stop the Python interpreter, this event is raised. If the code doesn’t handle it, it makes the interpreter quit.|
|TypeError||Thrown when an operation or function is tried that doesn’t work with the data type that was given.|
|ValueError||An error occurs when a built-in operation or function receives an argument that has the right type but an invalid value.|
|RuntimeError||Raised when a mistake can’t be put into any of the other categories.|
|NotImplementedError||This error is shown when a class that has been inherited doesn’t implement an abstract method that it should.|
In summary, an exception is a Python object that represents an error. There can be multiple except blocks for a single try block. You can throw an exception by using the raise keyword in Python. Consider the best practices in Python exception handling in doing your program.
Finally, if you missed any of our earlier lectures, you can always go to our Python Tutorial Topics list.