Identify and fix any potential errors in this code, or to suggest improvements for better error handling. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Identify and fix any potential errors in this code, or to suggest improvements for better error handling.

https://code.sololearn.com/cmHzqrqwjGSM/?ref=app

15th May 2023, 8:25 AM
Vibhor
Vibhor - avatar
9 Answers
+ 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”.
15th May 2023, 8:34 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 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
15th May 2023, 10:59 AM
Lothar
Lothar - avatar
+ 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
15th May 2023, 8:38 AM
Vibhor
Vibhor - avatar
+ 6
Ugulberto Sánchez Yes I got the point actually.
15th May 2023, 8:40 AM
Vibhor
Vibhor - avatar
+ 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/
15th May 2023, 8:42 AM
Tibor Santa
Tibor Santa - avatar
+ 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
15th May 2023, 8:31 AM
Vibhor
Vibhor - avatar
+ 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
15th May 2023, 8:28 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 4
Yw 😊 hope that it helped a lot
15th May 2023, 8:39 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 4
Vibhor read Tibor Santa comment. Sometimes except block can hide unexpected errors
15th May 2023, 8:44 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar