Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global exception handling

I want to catch KeyboardInterrupt globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement. Is there any way to do this?

like image 462
Kye Russell Avatar asked Jul 06 '11 14:07

Kye Russell


People also ask

What is global exception handling?

The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.

How does Python handle all errors?

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 raise a general exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Which exception catch all exceptions in Python?

Try and Except Statement – Catching all Exceptions Try 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.


2 Answers

You could change sys.excepthook if you really don't want to use a try/except.

import sys def my_except_hook(exctype, value, traceback):     if exctype == KeyboardInterrupt:         print "Handler code goes here"     else:         sys.__excepthook__(exctype, value, traceback) sys.excepthook = my_except_hook 
like image 61
multipleinterfaces Avatar answered Sep 20 '22 14:09

multipleinterfaces


If this is a script for execution on the command line, you can encapsulate your run-time logic in main(), call it in an if __name__ == '__main__' and wrap that.

if __name__ == '__main__':     try:         main()     except KeyboardInterrupt:         print 'Killed by user'         sys.exit(0) 
like image 36
Rob Cowie Avatar answered Sep 18 '22 14:09

Rob Cowie