Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Catch All Exceptions

Python – Catch All Exceptions

In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let’s see different types of errors in Python.

There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let’s see the difference between them.

Difference between Syntax Error and Exceptions

Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program.

Example: Syntax Error in Python

Python3




# initialize the amount variable
amount = 10000
  
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")


Output:

SyntaxError: invalid syntax

Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.

Example: Exception in Python

Python3




# initialize the amount variable
marks = 10000
  
# perform division with 0
a = marks / 0
print(a)


Output:

ZeroDivisionError: division by zero

Try and Except Statement – Catching all Exceptions

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

Example: Python catch all exceptions

Python3




# Python program to handle simple runtime error
  
a = [1, 2, 3]
try:
    print ("Second element = %d" %(a[1]))
  
    # Throws error since there are only 3 
    # elements in array
    print ("Fourth element = %d" %(a[3]))
  
except:
    print ("Error occurred")


Output

Second element = 2
An error occurred

In the above example, the statements that can cause the error are placed inside the try statement (second print statement in our case). The second print statement tries to access the fourth element of the list which is not there and this throws an exception. This exception is then caught by the except statement. Without specifying any type of exception all the exceptions cause within the try block will be caught by the except block. We can also catch a specific exception. Let’s see how to do that.

Catching Specific Exception

A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are –

try:
   # statement(s)
except IndexError:
   # statement(s)
except ValueError:
   # statement(s)

Example: Catching specific exception in Python

Python3




# Program to handle multiple errors with one
# except statement
# Python 3
  
def fun(a):
    if a < 4:
  
        # throws ZeroDivisionError for a = 3
        b = a/(a-3)
  
    # throws NameError if a >= 4
    print("Value of b = ", b)
      
try:
    fun(3)
    fun(5)
  
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
    print("ZeroDivisionError Occurred and Handled")
except NameError:
    print("NameError Occurred and Handled")


Output

ZeroDivisionError Occurred and Handled

If you comment the line fun(3), the output will be

NameError Occurred and Handled

The output above is so because as soon as python tries to access the value of b, NameError occurs. 

Note: For more information, refer to our Python Exception Handling Tutorial.

RELATED ARTICLES

Most Popular

Recent Comments