¿Cómo cuento las excepciones cuando se plantean?

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:

Parte 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?

Hasta ahora este es mi código:

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?

preguntado el 30 de enero de 12 a las 19:01

Tag with homework... and show us your barebone code -

1 Respuestas

I would suggest reading through Python's documentation on Errores y excepciones. 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

Respondido el 30 de enero de 12 a las 23:01

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? - JDx

@JDx - Your function is named check_for_exceptions, but according to the error you tried to call check_for_exception (note the missing 's'). Your code still may not work properly though, because func is passed in as its own argument to check_for_exceptions. This means that instead of calling self.func(), deberías llamar func(). - Andrew Clark

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.