What is the usage of the ‘raise’ in try and except statements?
I haven’t learnt about it before and codecademy just brought it here out of blue. I am confused.
raise raises an exception. Raising exceptions can be very useful. In programming its common to encounter new concepts, there is nothing wrong about using google to help you gain information
I experimented with the ‘raise’ function and the try / except statements, and am confused by how it works exactly.
If I include an except statement that matches the type of error that my try statement results in, then the except statement is executed (provided my try statement has an error).
But if I want my except statement to raise an error - it will raise both the actual error that the try statement results in, plus the error I have specified after the raise function.
Eg -
try:
1/0
except:
raise ValueError
This code above results in both a ZeroDivisionError (because of the try statement error) and the ValueError that I wanted. However, I would expect it only to result in the ValueError.
thankfully not, then you would loose the stacktrace and the error becomes very hard to trace
Currently, your try except only contains one line, but if it where several lines, or even several function calls, loosing the stacktrace would make it very difficult to determine where the error originated.
Ok thanks for the quick reply.
I think I understand.
However I wanted to know why this is the case.
If I code a try and except statement it will execute whatever is under the except statement - it does not mention the error that the try statement results in. So if I include a print function under my except statement, it will print and nothing else.
So if I raise an error under my except statement, why does it also mention the error occurring in the try statement?
Are you suggesting that because the raise function I have included is raising a type of error that does not match the error from the try statement - then both errors are displayed in order to keep the actual error from being hard to trace?
How come in this exercise, our alternative statement ( the ‘except’ statement) was printed (print("You have made a ValueError)) but in previous examples ( if, else…) the statements weren’t printed, they were just stated?
I came across mutiple exercises regarding “Try and Except” but it seems like this chapter has been removed from the latest syllabus. Could anyone help explain what happened, and where should I learn this concept now?