Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch all exceptions except user abort

I have a script that catches all exceptions, which works great unless I want to abort the script manually (with control + c). In this case the abort command appears to be caught by the exception instead of quitting.

Is there a way to exclude this type of error from the exception? For example something as follows:

try:
    do_thing()
except UserAbort:
    break
except Exception as e:
    print(e)
    continue
like image 854
AlexG Avatar asked Mar 19 '18 21:03

AlexG


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 except 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!”)

How do you catch all the exceptions?

We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.


1 Answers

You could just force to exit the program whenever the exception happens:

import sys
# ...
try:
    do_thing()
except UserAbort:
    break
except KeyboardInterrupt:
    sys.exit()
    pass
except Exception as e:
    print(e)
    continue
like image 78
Adriano Martins Avatar answered Oct 28 '22 11:10

Adriano Martins