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

问题描述 投票:0回答:2

如何在单个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!")
python try-except
2个回答
1
投票

Python相信显式异常处理。如果您的目的是只知道哪一行导致异常,那么不要去多个异常。在您的情况下,您不需要单独的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())

这将打印哪一行导致错误


0
投票

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

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

你也可以简单地捕获一个通用的Exception,这对于在运行时必须保持程序执行时很方便,但最好的做法是避免这个并捕获特定的异常而不是

希望这可以帮助!

可能是this的副本?

© www.soinside.com 2019 - 2024. All rights reserved.