简体   繁体   English

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

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

How to catch exception for multiple validation in a single try block ? 如何在单个try块中捕获多个验证的异常? Is it possible or do I need to use multiple try block for that ? 有可能还是我需要使用多个try块? 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. Python相信显式的异常处理。 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 您也可以简单地捕获一个通用的Exception ,这对于在运行时必须维护程序执行时非常方便,但是最好的方法是避免这种情况并捕获特定的异常

Hope this helps! 希望这可以帮助!

Possibly a duplicate of this ? 可能与重复吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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