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!")
Ja8zyjits
  • 1,433
  • 16
  • 31
Tsmk
  • 13
  • 2

2 Answers2

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

Ja8zyjits
  • 1,433
  • 16
  • 31
  • 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 Mar 19 '19 at 04:50
  • @Tsmk if the validations are same i.e `int()` 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? – Ja8zyjits Mar 19 '19 at 11:10
0

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?

Jack Branch
  • 152
  • 8
  • 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) – jfaccioni Mar 18 '19 at 12:11