If except can handle common errors very well, doesn't that make the use of raise redundant inside of a try-except block? For example: try: print( 5 / 0 ) except ZeroDivisionError: raise ValueError("An error occurred!") What's the difference if we handle it this way: try: print( 5 / 0 ) except (ZeroDivisionError, ValueError): print("An error occurred!") | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

If except can handle common errors very well, doesn't that make the use of raise redundant inside of a try-except block? For example: try: print( 5 / 0 ) except ZeroDivisionError: raise ValueError("An error occurred!") What's the difference if we handle it this way: try: print( 5 / 0 ) except (ZeroDivisionError, ValueError): print("An error occurred!")

8th Aug 2016, 9:32 PM
Bashar Ghadanfar
Bashar Ghadanfar - avatar
2 Answers
+ 1
The main difference is that your first example will halt the program, while the second will print an error and the program will carry on its merry way. Use raise if you are looking for a quick, easy method of halting the program and providing diagnostics, and try is a good keyword to use if you want the program to either carry on, or to prevent the program from crashing when the user runs it, giving a much more professional look. It's all up to you!
1st Mar 2017, 3:18 PM
Lelearner
0
a couple of thoughts: 1. when you do your own error handling, you can customize the error thrown, log it if you want, give more specific error, etc. The latter because you'll find some pretty generic errors thrown that aren't always very helpful in debugging 2. using try, except, finally gives more control in the many cases your program can't possibly know all possible combinations (user input, data streams over a socket, etc.) This is also much more secure coding. I've mentioned in other posts, most exploits are created due to improper error handling (language-agnostic fact)
9th Aug 2016, 1:32 AM
Izz
Izz - avatar