OmegaO333
OmegaO333

Reputation: 67

Use different handling ways in except clause

Is there any better way to do the following:

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Can't do 10 / 0")

try:
    print(20 / 0)
except ZeroDivisionError:
    print("Can't do 20 / 0")

I want to do two different things that may result in the same exception and handle them differently.

There is probably no way to do this. I just want to make sure.

Note: I know that in the above example, I can use variables, but I will be using this pattern for more complex things and don't want this solution.

Upvotes: 0

Views: 67

Answers (2)

Cowboy8625
Cowboy8625

Reputation: 11

To my knowledge I do not believe this is possible. If it was different Errors that wouldn't be hard

try:
    y = square(input('Please enter a number\n'))
        print(y)
    except (ValueError, TypeError) as e:
        print(type(e), '::', e)

to

try:
    y = square(input('Please enter a number\n'))
    print(y)
except ValueError as ve:
    print(type(ve), '::', ve)
except TypeError as te:
    print(type(te), '::', te)

But because you want it to be the same error type without the use of checking variables I do not believe there is a way.

Upvotes: 1

Ash
Ash

Reputation: 183

You can try nesting exceptions. You can try handling the first error and if that passes, except the 2nd. Without seeing exactly what you're doing, it's hard to say. Below is an example of handling multiple exceptions. Here's a tutorial for exceptions that also might help clear up the subject. https://realpython.com/python-exceptions/#raising-an-exception

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)

Upvotes: 0

Related Questions