Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PYTHON:如何在try块中捕获多个验证的异常?_Python_Try Except - Fatal编程技术网

PYTHON:如何在try块中捕获多个验证的异常?

PYTHON:如何在try块中捕获多个验证的异常?,python,try-except,Python,Try Except,如何在单个try块中捕获多个验证的异常?是否可能,或者我是否需要使用多个try块?这是我的密码: 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") ex

如何在单个try块中捕获多个验证的异常?是否可能,或者我是否需要使用多个try块?这是我的密码:

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

您确实可以在一个块中捕获两个异常,可以这样做:

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
您还可以简单地捕获一个通用的
异常
,这在运行时必须维护程序执行时非常方便,但最好避免这种情况,而是捕获特定的异常

希望这有帮助


可能是?

Python的副本,它相信显式异常处理。如果您的目的是只知道哪一行导致异常,那么不要选择多个异常。在您的情况下,您不需要单独的异常处理程序,因为您没有基于引发异常的特定行执行任何条件操作

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())

这将打印导致错误的行

OP的问题是在同一个try上没有捕获不同类型的异常/except,它知道try子句(
a=
b=
)中的哪个部分引发了相同的异常(
ValueError
,在这种情况下),如果您得到了正确的答案,您可以在最合适的答案上打勾,谢谢您的宝贵意见。但是,假设我有20次验证,我想知道具体是哪个导致了问题。我是否有可能或者必须为它们创建单独的try块。@Tsmk如果验证是相同的,即
int()
,那么这将是首选方法。如果还有其他验证器,则使用它们的异常,如
KeyError
等,这将帮助您根据异常类型进行区分。您是否为每次验证执行任何特定操作?