0

How to catch exception for multiple validation in a single try block ? Is it possible or do I need to use multiple try block for that ? Here is my code :

import sys

def math_func(num1, num2):
    return num1*num2

a,b = map(str,sys.stdin.readline().split(' '))
try:
    a = int(a)        
    b = int(b)
    print("Result is - ", math_func(a,b), "\n")
except FirstException: # For A
    print("A is not an int!")
except SecondException: # For B
    print("B is not an int!")
2

2 Answers 2

1

You can indeed catch two exceptions in a single block, this can be done like so:

import sys
def mathFunc(No1,No2):
    return No1*No2
a,b = map(str,sys.stdin.readline().split(' '))
    try:
        a = int(a)        
        b = int(b)
        print("Result is - ",mathFunc(a,b),"\n")
    except (FirstException, SecondException) as e: 
        if(isinstance(e, FirstException)):
            # put logic for a here
        elif(isinstance(e, SecondException)):
            # put logic for be here
        # ... repeat for more exceptions

You can also simply catch a generic Exception, this is handy for when program excecution must be maintained during runtime, but it is best practice to avoidthis and catch the specific exceptions instead

Hope this helps!

Possibly a duplicate of this?

Sign up to request clarification or add additional context in comments.

1 Comment

OP's problem isn't catching different types of Exceptions on the same try/except, it's knowing which part inside the try clause (a = or b =) raises the same Exception (ValueError in this case)
1

Python believes in explicit Exception handling. If your intention is to only know which line causes the exception then don't go for multiple exception. In your case you don't need separate Exception handlers, since you are not doing any conditional operation based on the specific line raising an exception.

import sys
import traceback

def math_func(num1, num2):
    return num1*num2

a,b = map(str, sys.stdin.readline().split(' '))
try:
    a = int(a)        
    b = int(b)
    print("Result is - ", math_func(a,b), "\n")
except ValueError: 
    print(traceback.format_exc())

This will print which line cause the error

2 Comments

thanks for your valuable comments. But, suppose I've like 20 validations and I want to know specifically which causing the problem. Is it possible or do I've to create separate try block for them all.
@Tsmk if the validations are same i.e int(<any_variable>) then this would be the preferred way. If there are other validators then use their exceptions like KeyError etc. That will help you to differentiate based on type of exceptions. Are you doing any specific operation for each validation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.