Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: try-catch-else without handling the exception. Possible?

I am new to python and is wondering if I can make a try-catch-else statement without handling the exception?

Like:

try:
    do_something()
except Exception:
else:
    print("Message: ", line) // complains about that else is not intended
like image 471
Rox Avatar asked May 05 '12 17:05

Rox


2 Answers

The following sample code shows you how to catch and ignore an exception, using pass.

try:
    do_something()
except RuntimeError:
    pass # does nothing
else:
    print("Message: ", line) 
like image 137
Jochen Ritzel Avatar answered Oct 17 '22 07:10

Jochen Ritzel


While I agree that Jochen Ritzel's is a good answer, I think there may be a small oversight in it. By passing, the exception /is/ being handled, only nothing is done. So really, the exception is ignored.

If you really don't want to handle the exception, then the exception should be raised. The following code makes that change to Jochen's code.

try:
    do_something()
except RuntimeError:
    raise #raises the exact error that would have otherwise been raised.
else:
    print("Message: ", line) 
like image 35
inspectorG4dget Avatar answered Oct 17 '22 06:10

inspectorG4dget