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