+ 4
Identify and fix any potential errors in this code, or to suggest improvements for better error handling.
9 odpowiedzi
+ 4
Vibhor Catching specific exceptions to print custom error messages is better than just catching all exceptions and print “something went wrong”.
But sometimes, if you already have caught the most common exceptions, catching the other exceptions (EOF, etc.) with a except block isn’t bad, so you print “the input isn’t correct”.
+ 9
Vibhor ,
what can be done is to use a very basic way to get all exceptions without naming them explicitly:
try:
... some code
except Exception as e:
print("this error occurred:", e)
see the example in the attached file.
https://code.sololearn.com/cWmzR9xiA3W0/?ref=app
+ 7
Ugulberto Sánchez Regarding catching other exceptions with a general except block for cases like EOF, your suggestion makes sense. It can be useful to catch unexpected or less common exceptions that might not be caught by specific exception handlers. Got it , Thank You
+ 6
Ugulberto Sánchez Yes I got the point actually.
+ 6
Using except without specifying the type of error, is in reality bad practice, because when something really unexpected happens, it can go unnoticed. In those cases it may be a better idea to let the program actually crash, then you can examine what went wrong and prepare the code to handle it gracefully.
Certainly NEVER do something like this, silently ignoring exceptions:
except:
pass
More on topic:
https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-exceptions/
+ 5
What are the advantages and disadvantages of this approach compared to handling specific exceptions? Is it considered a best practice in Python? Ugulberto Sánchez
+ 4
It seems fine. If you want to catch al, exception, just put except block at the end, without the specific exception you want to catch
+ 4
Yw 😊 hope that it helped a lot
+ 4
Vibhor read Tibor Santa comment. Sometimes except block can hide unexpected errors