Python Exception Handling Best Practices

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.

Example:

a = 7
b = 0

print (a/b)

Output:

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.

Example:

try:
     print(x)
except:
     print("An exception occurred.")

Output:

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")

Output:

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.

Example:

try:
      print('50'+20)
      print(7/0)
except (TypeError,ZeroDivisionError):
      print("Invalid input")

Output:

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.

Example:

try:
     print(7/0)

except ValueError:
     print('Value Error is raised')

finally:
     print('Prints the finally block')

Output:

Prints the finally block
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

Raise Exceptions

You might need to throw an exception to handle a situation.

You can throw an exception by using the raise keyword.

Example:

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

Output:

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.

Example:

raise ValueError("Enter a appropriate value")

Output:

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 NameDescription
ExceptionBase class for all exceptions
StopIterationThrown when an iterator’s next() method doesn’t point to any object.
SystemExitThe sys.exit() function raises this error.
StandardErrorExcept for StopIteration and SystemExit, this is the base class for all built-in exceptions.
ArithmeticErrorBase class for all errors that can happen when working with numbers.
OverflowErrorRaised when a calculation uses more numbers than a numeric type can handle.
FloatingPointErrorRaised when a calculation with a floating point number fails.
ZeroDivisionErrorRaised 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
AssertionErrorIf the Assert statement fails, this event is raised.
AttributeErrorIf the reference or assignment of an attribute fails, this event is raised.
EOFErrorIf the reference or assignment of an attribute fails, this event is raised.
ImportErrorIf an import statement fails, this event is thrown.
KeyboardInterruptWhen the user stops the program from running, usually by pressing Ctrl+c, this signal is sent.
LookupErrorBase class for the exceptions that are thrown when a key or index used on a mapping or sequence is not valid.
IndexErrorThrown when a sequence can’t find an index.
KeyErrorRaised when the key does not exist in the dictionary.
NameErrorRaised when an identifier can’t be found in either the local or global namespace.
UnboundLocalErrorRaised when a reference tries to use a local variable in a function or method that hasn’t been given a value yet.
EnvironmentErrorThis is the base class for all exceptions that happen outside of Python.
IOErrorRaised when an input/output operation fails, like when the print statement or the open() function try to open a file that doesn’t exist.
SyntaxErrorRaised when there is a mistake in the way Python is written.
IndentationErrorRaised when indentation is not specified properly.
SystemErrorRaised when the interpreter finds an internal error. However, when this error is thrown, the Python interpreter does not close.
SystemExitWhen 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.
TypeErrorThrown when an operation or function is tried that doesn’t work with the data type that was given.
ValueErrorAn error occurs when a built-in operation or function receives an argument that has the right type but an invalid value.
RuntimeErrorRaised when a mistake can’t be put into any of the other categories.
NotImplementedErrorThis error is shown when a class that has been inherited doesn’t implement an abstract method that it should.
List of Standard Exceptions in Python

Summary

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.


Leave a Comment