Open In App

How to Catch Multiple Exceptions in One Line in Python?

Improve
Improve
Like Article
Like
Save
Share
Report

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 to handle exceptions we use try/Except methods to get the exceptions. Previously we use them which makes our code complex and does not follow the DRY method of coding

Python3




a = 1
strs = "hello"
 
def func(a):
    res = a + strs
    print(res)
 
try:
    func(a)
except(TypeError)as e:
    print(e)
except(UnboundLocalError) as e:
    print(e)


 Output:

Typeerror

We can write this format in a form of passing the tuple into our except. Here we can write the print statement or any other doings only once and declare exceptions in a single line

Python3




a = 1
strs = "hello"
 
def func(a):
    res: a + strs  # unboundlocalerror
    print(res)
 
try:
    func(a)
except(TypeError, UnboundLocalError) as e:
    print(e)


Output:

local variable 'res' referenced before assignment

Last Updated : 02 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads