简体   繁体   中英

How do I count exceptions when they are raised?

I'm a beginner in programming and I'm having a bit of trouble with the basics of exceptions since I'm working on an exercise right now.

There are two parts to the exercise:

Part A:

I am required to create a class called ExceptionCounter that contains one instance variable, num_exceptions, which starts at 0. ExceptionCounter also has one method, which takes one parameter, a function (in addition to the usual self). check_for_exception calls the function (with no arguments) and increments num_exceptions if any exception is raised.

I have the barebones of the code down except for the part "if any exception is raised". I am passing through a function in which the function body is an object right? So if the function I'm passing has an error, how do I work with that error so that it triggers the increment?

So far this is my code:

class ExceptionCounter(Exception):
    def __init__(self):
        self.num_exceptions = 0

    def check_for_exceptions(self, func):
        try:
            self.func()
        except Exception:
            self.num_exceptions += 1

But Im getting an 'ExceptionCounter' object has no attribute 'check_for_exception' error. Any ideas on how to fix this?

I would suggest reading through Python's documentation on Errors and Exceptions . As for the part you are having trouble with, use a try/except. Put the code that may raise the exception in the try clause, and the "if an exception is raised" code in the except clause. For example:

try:
    func()          # call the function
except Exception:
    counter += 1    # this line is only executed if an exception was raised

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