Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: is RuntimeError acceptable for general use?

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'
like image 468
Mark Harrison Avatar asked Jun 24 '15 19:06

Mark Harrison


People also ask

What is Runtimeerror Python?

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.

Can I use try without Except?

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.

What are the 3 types of errors in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

How does Python handle general exceptions?

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.


1 Answers

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.

like image 107
Kevin Avatar answered Oct 13 '22 17:10

Kevin