Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling all but one exception

How to handle all but one exception?

try:
    something
except <any Exception except for a NoChildException>:
    # handling

Something like this, except without destroying the original traceback:

try:
    something
except NoChildException:
    raise NoChildException
except Exception:
    # handling
like image 214
Ivan Vulović Avatar asked Apr 20 '13 18:04

Ivan Vulović


People also ask

How do you handle multiple exceptions with a single except clause?

You can also handle multiple exceptions using a single except clause by passing these exceptions to the clause as a tuple . except (ZeroDivisionError, ValueError, TypeError): print ( "Something has gone wrong.." ) Finally, you can also leave out the name of the exception after the except keyword.

How do you handle different exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

Can you have multiple Except statements handle?

🔹 Multiple Except ClausesA try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed.

Can we have multiple except blocks while handling exceptions?

Python Multiple Exception in one ExceptYou can also have one except block handle multiple exceptions. To do this, use parentheses. Without that, the interpreter will return a syntax error.


2 Answers

The answer is to simply do a bare raise:

try:
    ...
except NoChildException:
    # optionally, do some stuff here and then ...
    raise
except Exception:
    # handling

This will re-raise the last thrown exception, with original stack trace intact (even if it's been handled!).

like image 99
Gareth Latty Avatar answered Oct 13 '22 22:10

Gareth Latty


New to Python ... but is not this a viable answer? I use it and apparently works.... and is linear.

try:
    something
except NoChildException:
    assert True
except Exception:
    # handling

E.g., I use this to get rid of (in certain situation useless) return exception FileExistsError from os.mkdir.

That is my code is:

try:
  os.mkdir(dbFileDir, mode=0o700)
except FileExistsError:
  assert True

and I simply accept as an abort to execution the fact that the dir is not somehow accessible.

like image 2
dario1001 Avatar answered Oct 13 '22 21:10

dario1001