-2

Let's assume, a code consists of nearly 50 lines, and it has a try block. Consider a case that the try block has 10 unknown errors. Is it possible to handle those exceptions without specifying the name of the error in the except clause?

Here is the sample code:

try:
    a = 2
    b = 2 / 0
    if 7 > 5:
        print(7)
except(ZeroDivisionError, IndentationError)
    print("Exception Handled")

In the above case, I know the name of the errors that occurred in the try block(say- ZeroDivisionError and IndentationError) What if the name of the error is unknown?

me_sarav
  • 21
  • 1

3 Answers3

1
try:
   #maliciousCodeFound
except:
   #catches ANY exception

except here Catches every error encountered in try block, you don't need to specify type of exception. However, if you want to catch and handle a specific type of exception(eg. Arithmetic Exception), you might wanna use this to handle that specific case. Otherwise just use except.

1

Put all the exceptions you want to catch in a tuple like so:

try:
    a = 2
    b = 2 / 0
    if 7 > 5:
        print(7)
except (ZeroDivisionError, IndentationError) as e:
    print("Exception:", e)

Outputs: Exception: division by zero

GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • My question is to handle the exception without specifying it in the except clause – me_sarav Jun 20 '19 at 13:15
  • Oh I see, my bad. AlmightyHeathcliff's answer is probably what you want. It catches ALL exceptions. What do you have in mind, though? "What if the name of the error is unknown" Why might it be unknown? – GordonAitchJay Jun 20 '19 at 13:19
1

Exception hierarchy

Most exceptions are subclasses of the Exception class. But this is not true of all exceptions. Exception itself actually inherits from a class called BaseException. In fact, all exceptions must extend the BaseException class or one of its subclasses.

Exception derives directly from BaseException and the exceptions that we handle usually derive from Exception. There are two key exceptions, SystemExit and KeyboardInterrupt, that derive directly from BaseException instead of Exception. When we use the except: clause without specifying any type of exception, it will catch all subclasses of BaseException; which is to say, it will catch all exceptions, including the two special ones.

So, don't use except:, use:

try:
    # thing you want to try
except Exception:
    # handle exception

EDIT:

try:
    a = 2
    print("The next step the program will catch an exception.")
    b = 2 / 0
    if 7 > 5:
        print("This will never run.")
        print(7)
except Exception:
    print("Exception Handled")

Andressa Cabistani
  • 463
  • 1
  • 5
  • 14