0

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?

28th Jan 2019, 10:54 AM
Farhan Khan
Farhan Khan - avatar
6 Respostas
+ 2
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.
28th Jan 2019, 12:05 PM
Zen
Zen - avatar
+ 1
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.
28th Jan 2019, 11:11 AM
James
James - avatar
+ 1
I edited my explanation. Try reading it again. Now I don't know how else to explain it... Sorry.
28th Jan 2019, 11:14 AM
James
James - avatar
+ 1
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. https://code.sololearn.com/c4JM6RUUPt9P/?ref=app
28th Jan 2019, 1:48 PM
HonFu
HonFu - avatar
+ 1
Nice. I'm getting it.
28th Jan 2019, 5:57 PM
Farhan Khan
Farhan Khan - avatar
0
James I couldn't get u 😢
28th Jan 2019, 11:12 AM
Farhan Khan
Farhan Khan - avatar