Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a `try`/`except` block that catches all exceptions?

How can I write a try/except block that catches all exceptions?

like image 931
user469652 Avatar asked Feb 14 '11 09:02

user469652


People also ask

Does except exception catch all exceptions?

Try and Except Statement – Catching all ExceptionsTry and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

What can be used in the except block to catch all exceptions?

We can specify which exceptions an except clause should catch. A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.

How do you catch all exceptions in Python?

Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)


2 Answers

You can but you probably shouldn't:

try:     do_something() except:     print("Caught it!") 

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:     f = open('myfile.txt')     s = f.readline()     i = int(s.strip()) except IOError as (errno, strerror):     print("I/O error({0}): {1}".format(errno, strerror)) except ValueError:     print("Could not convert data to an integer.") except:     print("Unexpected error:", sys.exc_info()[0])     raise 
like image 41
Tim Pietzcker Avatar answered Oct 07 '22 01:10

Tim Pietzcker


Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:

import traceback import logging  try:     whatever() except Exception as e:     logging.error(traceback.format_exc())     # Logs the error appropriately.  

You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.

like image 128
Duncan Avatar answered Oct 07 '22 00:10

Duncan