+ 4

A newbie question; we can use if else to overcome abnormal behaviour of our program then why we use exception handling??

8th Aug 2019, 5:06 PM
...
... - avatar
7 Réponses
+ 10
Simply there are some exceptions that you cannot avoid with if-else like IOException,sqlexception.. etc so instead of crashing your program you can handle these exceptions by try-catch blocks. In addition there are build-in classes's functions in java that throws some exceptions so you are obliged to actually handle these exceptions. edit : just to be accurate, you can avoid some exceptions with if-else, but using try catch is inevitable for some other exceptions.so when you use if-else you are not handling these exceptions but you are just avoiding these exceptions from happening . Hope this helps ^^.
10th Aug 2019, 2:52 PM
Anon Fox
Anon Fox - avatar
+ 4
Another example, your program relies on the user to enter a number. If they enter the wrong type of data, like some text or special character, or a number that is out of range compared to what you expect, then it might be much easier to use exception handling to defend against these cases, maybe give some meaningful feedback to the user.
8th Aug 2019, 5:19 PM
Tibor Santa
Tibor Santa - avatar
+ 4
Using too many if else statements can make the code messy.
9th Aug 2019, 1:14 AM
Sonic
Sonic - avatar
+ 3
Exception handling is there because we can't always "guarantee" that our program will run perfectly. For example, what if you're downloading a file and network gets interrupted? What if your program is running, and a user shuts down their computer.? Using if else will only triple the length of your code
8th Aug 2019, 5:12 PM
Dlite
Dlite - avatar
+ 2
The if... else pattern is a conditional pattern. It allows a programmer to alter what a program does based on certain conditions at runtime (e.g., if salary is more than 50000, add 5% bonus else add 3% bonus). Exception handling, on the other hand, is responsible for giving you control over how your program generates and handles errors, making your program more robust and less likely to crash when something happens that is abnormal (such as dividing by 0).
8th Aug 2019, 10:01 PM
Glenn
+ 2
Exception handling handles the exception for our need at runtime with the use of try and catch but the main purpose is to prevent abnormal termination of program and customise the exception message to our chosen.
8th Aug 2019, 11:16 PM
Austin.O
Austin.O - avatar
0
try catch isolates the case, tests it, and acts in consequence its very useful to manage input
10th Aug 2019, 3:16 PM
BinaryEden
BinaryEden - avatar