Is it acceptable to use the RuntimeError exception for general application use?
raise RuntimeError('config file is missing host address')
I've got some code with a couple of one-off situations like this and would prefer to avoid creating one-off exception classes for each of them. All the situations are fatal, and my goal is to get a clear message to the console. Basically I'm looking for something similar to the deprecated
raise 'config file is missing host address'
A run-time error happens when Python understands what you are saying, but runs into trouble when following your instructions. This is called a run-time error because it occurs after the program starts running. A program or code may be syntactically correct and may not throw any syntax error.
We cannot have the try block without except so, the only thing we can do is try to ignore the raised exception so that the code does not go the except block and specify the pass statement in the except block as shown earlier. The pass statement is equivalent to an empty line of code. We can also use the finally block.
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
This is... OK. Ideally, you would have separate exceptions for each reasonably distinct situation (e.g. one exception for all "the config file is malformed" errors, reuse FileNotFoundError
in 3.x for "the config file doesn't exist", etc.). But this is one of the more innocuous forms of technical debt.
The downside is that if you ever do introduce those separate exceptions, they may need to subclass from RuntimeError
for reasons of backwards compatibility. That's kind of ugly, but mostly harmless.
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