I have these files in my project:
- main.py
- module1.py
- module2.py
main
is the main file that will be directly execute in console.
module1
will be imported into main
and throws Module1Exception
.
module2
will be imported into module1
, throws Module2Exception
and uses lib that throws NormalException
and CriticalException
exceptions.
On all exceptions application should exit.
Which option is a most effective way to catch those errors?
a) All exceptions will be catch in main
, print message and exit
b) Lets allow modules to catch exceptions (module2
catch lib exceptions, module1
catch only Module2Exception
and main
catch Module1Exception
), print message and exit.
c) Like b, except that modules will not exit, instead returns False and exit will be called in main
Edit:
This will be server side application, running as daemon. I expect that in future I will be using multiple servers with global log monitoring, like flume or scribe. Exceptions must be caught. These files is only example. In fact, I'm writing a large application which is act as a kind of server. In this moment i write module for load and parse configuration file. In this case script should exit if any exceptions will be raised. And only in this case. After loading the configuration files and pass the tests, the script will be left unattended.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can't foresee at the time you're writing the code.
main
should have the responsibility to terminate, not the modules.
What if you wanted to import those modules into another project and you didn't want to terminate the application on an exception?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With