0

Exception Handling

As I understand while developing the software exception handling is crucial for a bug free software. I have a doubt how bug can be pinned down with try and except block. For following code: try: X=10 Y=2 print(X+"hello") print(X/Y) except ZeroDivisionError: print("Divided by zero") except (ValueError, TypeError): print("Error occurred") Output output is:: Error occurred In 2nd except: statement two type of errors were envisaged. My quarry is if while processing if code is not telling which error has occurred out of two or any other type of error has occurred which is not envisaged what's the use of writing such elaborate code. why not only except: statement. Same quarry is presented in different way if 2nd except is only" except: " even then there is no change in output. Looking for response.

14th Aug 2018, 4:43 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
3 Answers
+ 6
In line 4, you're trying to add a number and a string, so you'll raise a type error. As this kind of exception is caught in line 8, it will jump to line 9 and do whatever is specified there. In this case, it says only print('Error occurred'), so that's all what's going to happen. It won't give you any more information on what kind of error occurred etc., because you specifically caught type errors and told the interpreter what to do when a type error occurs (print 'Error occurred'). That's what exceptions are used for, you expect that a specific kind of error might occur, and you enable your program to react in a specific way. So it doesn't make any sense for the interpreter to inform you that a type error occurred, because you already predicted that.
14th Aug 2018, 6:48 PM
Anna
Anna - avatar
0
Thank you Anna for responding.In the mean time I was learning about raise method. You can experement code Sanjeev3. With raise method and Y=0, it clealy tells about type of error even though it was not predicted.raise statement within except block helps to find out the type of error and can identify type of unpredictable errors. Looking for further observation and suggestions .
15th Aug 2018, 1:15 AM
Sanjeev Kumar
Sanjeev Kumar - avatar
0
this is BS
19th Dec 2019, 1:26 PM
Tanbeer