Python

How to Catch All Exceptions in Python

In Python, the programs throw an exception when an error or fault appears in the code during execution. An exception is basically an object that represents an error in Python. Whenever the exception appears in the program, we need to handle it using different methods. There are multiple ways to handle or catch-all exceptions in Python.

This write-up provides an in-depth guide on catching all exceptions in Python using numerous examples.

How to Catch All Exceptions in Python?

To catch all exceptions, various methods are used in Python. Some of the methods are shown below:

Method 1: Catch All Exceptions Using “try” and “except” Statement

The “try” and “except” statements are employed to fetch/catch-all Python exceptions. The “try” statement is used to execute the program code and raise an exception, and the “except” statement handles the exception that is raised by the “try” statement. Let’s understand it via the below code:

list1 = [43, 32, 43, 53]
try:
    print(list1[1])
    print(list1[6])
except:
    print("Error Occurred While Accessing List Element")

 

In the above code:

  • The “try” block executes the code and accesses the list element placed at index “1” and “6” using the square bracket notion.
  • The “except” statement executes the code when the exception is raised by the “try” statement while accessing the list element at index “6” (that does not exist in the list).

Output

The exception has been caught successfully.

Now, we can utilize the “try-except” statement to catch specific exceptions such as ValueError, KeyError, and others. Here is an example code:

tuple1 = (45, 55, 65, 78)
try:
    print(tuple1[0])
    print(tuple1[4])
except IndexError:
    print('tuple index out of range')

 

In this code:

  • The “except” statement catches the specified “IndexError” which is raised by accessing the out-of-range element value “4” from the input tuple.
  • The “except” statement returns the exception message when the index error is raised.

Output

The specified exception has been caught successfully.

Method 2: Catch All Exceptions Using “raise” Exception

The “raise” exception can also be utilized to catch all the exceptions and display them to output. Here is an example code:

list1 = [1, 4, 5, 6]
list2 = [4, 5, 6, 7, 9]
if len(list1) == len(list2):
    print('True')
else:
    raise Exception('List Length is Not Equal')

 

In the above code:

  • The “list1” and “list2” are initialized in the program.
  • The “if” statement is used to check whether the given two lists are equal or not.
  • If the list is equal, the “print()” statement shows the specified message.
  • The “raise Exception” is used inside the “else” block to return the exception.

Output

The exception has been caught successfully.

Method 3: Catch All Exceptions Using “logger.exception”

The “logger.exception” method of the “logging” module logs an error, including the complete traceback information. This method can be used along with the “try-except” statement to catch all exceptions in Python. Here is an example code:

import logging
logger=logging.getLogger()
try:
    num1 = 12
    num2 = 0
    print(num1/num2)
except Exception as z:
    logger.exception("Exception Occurred:  " + str(z))

 

In the above code:

  • The “logging” module is imported.
  • The “logger” object is created and used to write the log’s message to the file or consoles and others.
  • In the “try” block, the “exception” is raised when the specified number is divided by the “zero”.
  • While in the “except” block, the “exception” is caught by the “logger.exception()” method. This method creates a log error message, including traceback information.

Output

Conclusion

The “try” and “except” statement, the “raise” exception, and the “logger.exception” method are utilized to fetch/catch all exceptions in Python. The “try-except” statement is utilized to fetch/catch all the exceptions and specified exceptions. The “raise Exception” and “logger.exception” method can easily fetch or catch the exception in Python. This write-up delivered a comprehensive tutorial on catching all exceptions in Python using numerous examples.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.