Use of exceptions?? | SoloLearn: Learn to code for FREE!


Use of exceptions??

Could anybody please explain me why we use the catch throw and try words when we can custom design our own function using return and if commands? I mean what is the use of having exceptions?

1/28/2019 10:54:28 AM

Farhan Khan

6 Answers

New Answer


Practically, the exceptions you catch will be from other functions you are using in your function. And you can't do what you said in that case. James, an error is not an exception, they are not supposed to be caught, they mean that something went very wrong and that the program execution has to stop.


Edit: Maybe I am wrong. Perhaps the code has not received an important variable yet from a database. When you run the code that needs the variable, it creates an error that stops all of the code, even if the remaining code has no errors. If instead you use try and catch, then the error will not stop the whole code.


I edited my explanation. Try reading it again. Now I don't know how else to explain it... Sorry.


When you're writing a function that is going to be used by someone else (who might be you six months later ^^) and they pass a wrong value to the function, instead of returning just some arbitrary value, you might want to throw an error instead, so that the user gets a clear signal of what's wrong instead of letting the program continue with wrong or no values. Let me link an example. My function can not handle values sub zero or bases higher than 36, so if that gets passed as an argument, there'll be an error. So you could embed the function call in a try-except structure to catch that error in a way that's fitting for your program. For example if user input contains wrong values, instead of terminating the program, you could give out an error message and let them input again.


Nice. I'm getting it.


James I couldn't get u 😢