+ 4
What is the point in raising an exception?
Can someone explain why do I need to raise an exception? If possible I'd like to see a real application of raise. Thanks!
6 Respuestas
+ 5
Exception can be of use to prevent corrupted data from getting insert as input in forms. For example a program written to collect data through an interactive survey may get corrupted data as input, deliberately or by mistake. An exception can be used in anm program to reject inputs that are corrupt
+ 3
it is useful as if user enters the operation 10 / 0 then instead of the whole lot of error lines it would display a small message and would be understandable by the user
+ 3
What's important is actually handling exceptions, not just raising them.
+ 3
You need exceptions to signal error conditions out of band, especially when writing modules for use by others. For example, when writing an optimization module that returns a result based on certain user-defined constraints, you have to decide what to do if no solution can be found because the constraints are contradictory. To communicate this situation to the caller of your optimization function, you have basically two options: return a special value that indicates an error, or throw an exception. Returning special values forces your caller to always check the result for all possible special values and to handle them immediately, breaking the regular program flow. If your function were to throw exceptions instead, callers can simply write down the normal sequence of events and do error handling in the except blocks - or omit it entirely and delegate it to *their* callers.
+ 3
When an unhandled exception occurs your program breaks. It crashes to desktop and the user looses progress of whatever they were doing. That is bad.
This happens because something unexpected occured and the program doesn't know what to do with it, so it rather break and display an error. Raising an exception tells the program "Chill out, it's cool. An exception was expected. Keep calm and carry on".
Preventing your program from breaking is one thing, fixing the issue (a.k.a. handling the exception) is even better. say you want to add user input to user input in sum() but the user decides to add int 5 to string "spam". Should we break the program? Nah. Let's rise an exception and handle it by saying that if it's not an int or float the program should ask again.
+ 2
for example if you are using your program to talk to another program or read a value from a database, you are not 100% sure that the endpoint you are talking to will answer you back f.ex. because of a timeout and you want to have a pre-defined reaction.
F.ex. if you are supposed to get a array from some method call and for one or another reason you get null back you will get a null pointer exception if you try to print or select from the array