简体   繁体   中英

PYTHON : How to catch exception for multiple validation in try block?

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!")

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

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM