简体   繁体   中英

Try / Except all Python errors of a certain type

In my Python code, I'm using the PyQt5 module to display a GUI. Sometimes, I encounter a Runtime Error if I delete an element then attempt to use a function on the element's instance. This error is only displayed in the console, and it does not actually interfere with the GUI or terminate it.

Regardless, I would like to remove it (the Runtime Errors). My first thought was to use a try/except block on the code, and except the Runtime Error that I was talking about. The problem with this, is that if I encase my whole code with the try/except block, then if the error is caught, it will skip over to the end of my program and terminate:

try:
    # If any errors occur here...
    <code>
except RuntimeError:
    # The GUI will stop entirely, and the Python interpreter will skip to this line
    pass

Another solution to my problem is to encase any instance which could throw a RuntimeError with a try/catch block, like so:

try:
    # If any errors occur here...
    <code that may print an error>
except RuntimeError:
    # Python wont display the error
    pass

However given the mass amount of times I would need to do this in my code, I was wondering if there was a more efficient way of fixing this problem.

You can use customs decorators to to this (I don't know your python level but it's not the most beginner friendly thing). For example, this code here do not raise any error:

from functools import wraps

def IgnoreError(f):
    @wraps(f)
    def wrapper():
        try:
            f()
        except ZeroDivisionError:
            pass
    return wrapper

@IgnoreError
def func1():
    x = 5/0

func1()

In your case, you will have to define this function:

def IgnoreError(f):
    def wrapper(*args, **kwargs):
        try:
            f(*args, **kwargs)
        except RuntimeError:
            pass
    return wrapper

and then anytime you create a function that may raise the RuntimeError, just put the decorator @IgnoreError before your definition like this:

@IgnoreError
def func():
   <your code here>

(if you want here's a video from TechWithTim explaining the decorators)

As per my comment, I would definitely go with the catch in the specific line calls that might throw the runtime error. This avoids you accidentally suppressing another error you were not anticipating.

Depending on what the calls are that might give the runtime error, I would prefer a decorator pattern to hide the try-except logic. Something like:

from functools import wraps


def catch_runtime_error(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except RuntimeError:
            pass  # or whatever handle you fancy

    return wrapper

which you would then use like:

@catch_runtime_error
def the_function_that_raises(...):
    # whatever the body is

the_function_that_raises(...)

Alternatively you can use it more directly in your code:

def the_function_that_raises(...):
    # whatever the body is

catch_runtime_error(the_function_that_raises)(...)

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