+ 2
Exception Handling Question
In the final module of the course, exception handling was covered. Although I already knew about the try, throw and catch statements, I never fully understood the point of them. In the example, they used something along the lines of this: try { int a, b; cin >> a >> b; if (b == 0) throw 0; cout << a / b; } catch(int x) { cout << "Cannot divide by zero! Error: " << x; } I fully understand what this code is doing, and why it's doing it. My question is what benefit does error handling like the one above, have over something like this?: int a, b; cin >> a >> b; if (b == 0) { cout << "Cannot divide by zero! Error: " << x; return 0; } cout << a / b; Many thanksđ
5 Answers
+ 3
Many thanks, guys! đ
+ 2
Could it be that the first error handling method ensures that the program doesn't crash due to the error, and ignores the part with the error, continuing on with the rest of the program (regardless of whether or not that error line was needed for the program in the future)?
+ 2
Well, this was just a simple case and you knew in advance that what could go wrong in your program. Consider a bigger more complex functionality. There will be so many more unexpected cases that could occur and are beyond your imagination. You see programs crashing all the time right. It's because of one such unexpected error. Let's say even if we know that there can be 100 things that can go wrong with a particular program, would you prefer to write 100 if-else specifying each condition or just enclose it in a single try catch which will handle it automatically?
+ 2
The try / throw / catch schema goes beyond the scope of your function where the exception happen.. a method inside a class can throw an exception that can be catched by any code that calls that method and then the exception can be treat it as needed in the calling code...
+ 1
When you want to design your code and use MVC, SOLID or ... You need this because it can help you for example inside of your class you throw some error and catch it in main or somewhere and print it with whatever you want. Your code can be reusable I think.