Write try/except block to catch all exceptions in Python

Error handling is the must having skills for any developers. In Python programming language we use try/except block for error handling or for catching exceptions. In this article we will learn how to write try/except block that catches all exceptions. But before that, let’s learn about errors and exceptions.

Table Of Contents

Errors vs Exception

Errors are the problems in our code which leads to the interruption of the execution of the current program and hence the programs stops. While exceptions are raised when due to some internal events the flow of program changes. In simple words, Errors that occur during compilation are called Syntax Error and Errors that occur during execution are called Exceptions. We have SYNTAX ERRORS and LOGICAL ERRORS which are also known as Exceptions.

Syntax Errors

If something is not as per as language grammar of the programming language, such as leaving out a symbol, such as colon, comma or braces or Incorrect indentation.

Exceptions

Errors that occur during execution are called Exceptions. Below are the built-in exceptions in the Python programming language:

  • ZeroDivisionError
  • IndexError
  • AssertionError
  • AttributeError
  • ImportError
  • KeyError
  • NameError
  • MemoryError
  • TypeError

Try/Except

Try and except blocks are used to deal with exceptions in python. Raising an exception in Python is same as throwing and exception in C++ and Java. Statements who think which may raise an exception should be enclosed in the try block. While the except block catches the raised exception in it.

If an exception is raised in the try block, then the rest of the try block is skipped and the control goes to the except block. Now if the exception raised is present inside the except block and matches the exception named after except keyword, then the except block is executed. Try block can be nested inside the try block. An empty except block catches all the exceptions.

See an Example of catching exceptions

CODE :

def average():
    try:
        # taking integer inputs.
        total = int(input('Enter total. '))
        # taking integer inputs.
        subjects = int(input("Enter number of subjects. "))
        percentage = total/subjects
        print("Your average marks is. ", percentage)
        # expecting a ZeroDivisionError which means denominator is zero.
    except ZeroDivisionError:
        print("Denominator can't be zero")

# calling function.
average()

When Input provided 222 for total and 3 for subjects.

OUTPUT :

Enter total. 222
Enter number of subjects. 3
Your average marks is. 74.0

When total is 300 and number of subjects is 0.

OUTPUT :

Enter total. 300
Enter number of subjects. 0
Denominator can't be zero

So, In the above code and output you can see we are expecting a ZeroDivisionError. You can see instead of interrupting the program, Python Interpreter moves to except block and checks whether user is expecting any error related to this. If exception was not handled then program would have stopped execution.

Now this was the case when the developer is aware about the exceptions he is expecting. What if you want to catch all the exceptions.
Below is an example

CODE :

def average():
    try:
        # taking integer inputs.
        total = int(input('Enter total. '))
        # taking integer inputs.
        subjects = int(input("Enter number of subjects. "))
        percentage = total/subjects
        print("Your average marks is. ", avg)
        # expecting error
    except:
        print('Some Error Occurred')

# calling function
average()

# checking for execution of program.
print('Program Executed')

OUTPUT 1:

Enter total. 500
Enter number of subjects. 6
Some Error Occurred
Program Executed

OUTPUT 2:

Enter total. 500
Enter number of subjects. 0
Some Error Occurred
Program Executed

In code and output above you can see we have a average function in try/except block. In this example, any specific exception has not been provided, instead we have used a print() method without any exceptions. This will catch all the exceptions raised. Like in output 1 we have a NameError, so as the Python Interpreter detects it as a NameError, instantly it goes to the except block and prints the message and the code gets executed. Again in output 2 we have a ZeroDivisionError because in number of subjects 0 has been provided, so when the denominator is zero Python throws a ZeroDivisionError.

SUMMARY

So, In this python tutorial article we learn about error handling in Python Programming language. We also learn about Syntax Errors and Exceptions and types of Exceptions in Python. Also we learned to write try/except block that catches all exceptions raised. It is always good to handle the exceptions which are expected in the program but you can also use the above method that will catch all exceptions raised.

Make sure to read and write example codes in order to have a better understanding of this problem.

Thanks

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top