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 exceptions in the Python

The code defines a function fun(a)' that calculates b based on the input a. If a is less than 4, it attempts a division by zero, causing a ZeroDivisionError'. The code calls fun(3) and fun(5) inside a try-except block. It handles the ZeroDivisionError for fun(3) and prints “ZeroDivisionError Occurred and Handled.” The NameError' block is not executed since there are no NameError' exceptions in the code.

Python3




def fun(a):
    if a < 4:
 
        b = a/(a-3)
    print("Value of b = ", b)
     
try:
    fun(3)
    fun(5)
except ZeroDivisionError:
    print("ZeroDivisionError Occurred and Handled")
except NameError:
    print("NameError Occurred and Handled")


Output

ZeroDivisionError Occurred and Handled

If you comment on 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. 

Python Exception Handling

We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4). 

In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the help of proper examples. 

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are 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 change the normal flow of the program. 

Different types of exceptions in python:

In Python, there are several built-in Python exceptions that can be raised when an error occurs during the execution of a program. Here are some of the most common types of exceptions in Python:

  • SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
  • TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer.
  • NameError: This exception is raised when a variable or function name is not found in the current scope.
  • IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.
  • KeyError: This exception is raised when a key is not found in a dictionary.
  • ValueError: This exception is raised when a function or method is called with an invalid argument or input, such as trying to convert a string to an integer when the string does not represent a valid integer.
  • AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to access a non-existent attribute of a class instance.
  • IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an input/output error.
  • ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
  • ImportError: This exception is raised when an import statement fails to find or load a module.

These are just a few examples of the many types of exceptions that can occur in Python. It’s important to handle exceptions properly in your code using try-except blocks or other error-handling techniques, in order to gracefully handle errors and prevent the program from crashing.

Similar Reads

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

Try and Except Statement – Catching Exceptions

...

Catching Specific Exception

...

Try with Else Clause

...

Finally Keyword in Python

...

Raising Exception

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