Exceptions for the whole class

2024/10/3 6:23:21

I'm writing a program in Python, and nearly every method im my class is written like this:

def someMethod(self):try:#...except someException:#in case of exception, do something here#e.g display a dialog box to inform the user #that he has done something wrong

As the class grows, it is a little bit annoying to write the same try-except block over and over. Is it possible to create some sort of 'global' exception for the whole class? What's the recommended way in Python to deal with this?

Answer

Write one or more exception handler functions that, given a function and the exception raised in it, does what you want to do (e.g. displays an alert). If you need more than one, write them.

def message(func, e):print "Exception", type(e).__name__, "in", func.__name__print str(e)

Now write a decorator that applies a given handler to a called function:

import functoolsdef handle_with(handler, *exceptions):try:handler, cleanup = handlerexcept TypeError:cleanup = lambda f, e: Nonedef decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):try:return func(*args, **kwargs)except exceptions or Exception as e:return handler(func, e)else:e = Nonefinally:cleanup(func, e)return wrapperreturn decorator

This only captures the exceptions you specify. If you don't specify any, Exception is caught. Additionally, the first argument can be a tuple (or other sequence) of two handler functions; the second handler, if given, is called in a finally clause. The value returned from the primary handler is returned as the value of the function call.

Now, given the above, you can write:

@handle_with(message, TypeError, ValueError)
def add(x, y):return x + y

You could also do this with a context manager:

from contextlib import contextmanager @contextmanager
def handler(handler, *exceptions):try:handler, cleanup = handlerexcept TypeError:cleanup = lambda e: Nonetry:yieldexcept exceptions or Exception as e:handler(e)else:e = Nonefinally:cleanup(e)

Now you can write:

def message(e):print "Exception", type(e).__name__print str(e)def add(x, y):with handler(message, TypeError, ValueError):return x + y

Note that the context manager doesn't know what function it's in (you can find this out, sorta, using inspect, though this is "magic" so I didn't do it) so it gives you a little less useful information. Also, the context manager doesn't give you the opportunity to return anything in your handler.

https://en.xdnf.cn/q/70757.html

Related Q&A

Getting live output from asyncio subprocess

Im trying to use Python asyncio subprocesses to start an interactive SSH session and automatically input the password. The actual use case doesnt matter but it helps illustrate my problem. This is my c…

multi language support in python script

I have a large python (2.7) script that reads data from a database and generate pictures in pdf format. My pictures have strings for labels, etc... Now I want to add a multi language support for the sc…

Add date tickers to a matplotlib/python chart

I have a question that sounds simple but its driving me mad for some days. I have a historical time series closed in two lists: the first list is containing prices, lets say P = [1, 1.5, 1.3 ...] while…

Python Selenium: Cant find element by xpath when browser is headless

Im attempting to log into a website using Python Selenium using the following code:import time from contextlib import contextmanager from selenium import webdriver from selenium.webdriver.chrome.option…

Reading large file in Spark issue - python

I have spark installed in local, with python, and when running the following code:data=sc.textFile(C:\\Users\\xxxx\\Desktop\\train.csv) data.first()I get the following error:---------------------------…

pyinstaller: 2 instances of my cherrypy app exe get executed

I have a cherrypy app that Ive made an exe with pyinstaller. now when I run the exe it loads itself twice into memory. Watching the taskmanager shows the first instance load into about 1k, then a seco…

python - Dataframes with RangeIndex vs.Int64Index - Why?

EDIT: I have just found a line in my code that changes my df from a RangeIndex to a numeric Int64Index. How and why does this happen?Before this line all my df are type RangeIndex. After this line of …

Uniform Circular LBP face recognition implementation

I am trying to implement a basic face recognition system using Uniform Circular LBP (8 Points in 1 unit radius neighborhood). I am taking an image, re-sizing it to 200 x 200 pixels and then splitting …

SQLAlchemy declarative one-to-many not defined error

Im trying to figure how to define a one-to-many relationship using SQLAlchemys declarative ORM, and trying to get the example to work, but Im getting an error that my sub-class cant be found (naturally…

Convert numpy.array object to PIL image object

I have been trying to convert a numpy array to PIL image using Image.fromarray but it shows the following error. Traceback (most recent call last): File "C:\Users\Shri1008 SauravDas\AppData\Loc…