Open In App

Python – Catch All Exceptions

Last Updated : 19 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Similar Reads

How to Catch Multiple Exceptions in One Line in Python?
Prerequisites: Exception handling in python There might be cases when we need to have exceptions in a single line. In this article, we will learn about how we can have multiple exceptions in a single line. We use this method to make code more readable and less complex. Also, it will help us follow the DRY (Don't repeat code) code method Generally t
1 min read
How to catch a NumPy warning like an exception in Python
An N-dimensional array that is used in linear algebra is called NumPy. Whenever the user tries to perform some action that is impossible or tries to capture an item that doesn't exist, NumPy usually throws an error, like it's an exception. Similarly, in a Numpy array, when the user tries to perform some action that is impossible or tries to capture
3 min read
How To Catch A Keyboardinterrupt in Python
In Python, KeyboardInterrupt is a built-in exception that occurs when the user interrupts the execution of a program using a keyboard action, typically by pressing Ctrl+C. Handling KeyboardInterrupt is crucial, especially in scenarios where a program involves time-consuming operations or user interactions. In this article, we'll explore how to catc
3 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python Python throws errors and
4 min read
Python | Catching and Creating Exceptions
Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code. Because of this, if one catches all exceptions, it is absolutely critical to log or reports the actual reason for the excep
2 min read
Exceptions - Selenium Python
Exceptions in Selenium Python are the errors that occur when one of method fails or an unexpected event occurs. All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generat
3 min read
Errors and Exceptions in Python
Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. Two types of Error occurs in python. Syntax errorsLogical errors (Exceptions) Syntax errors When the proper syntax of the language is not follow
3 min read
How To Fix Valueerror Exceptions In Python
Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Python. In this article, we will see some methods and
4 min read
Handle Unhashable Type List Exceptions in Python
Python, with its versatile and dynamic nature, empowers developers to create expressive and efficient code. However, in the course of Python programming, encountering errors is inevitable. One such common challenge is the "Unhashable Type List Exception". In this article, we will dive deep into the intricacies of Unhashable Type List Exception in P
3 min read
Concrete Exceptions in Python
In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python in detail with the help of examples. Concrete Excep
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg