why to use multiple catches in exception? - exception

when we can handle it in single default Exception then Why we should use
Multiple Catches?
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}

If you are using specific exception, let's say SqlException, it will take care of all the possible exceptions codes but in if-else ladder, you need to define all the possible scenarios and there is a high chance you might miss some of them.

Please format your question properly from next time. Try to add what you have tried to solve the issue and explain your approach as much as possible.
Coming to the actual answer, you use multiple exceptions to provide specific handling mechanisms for each type of exception.
For example, if you want to handle DivideByZero exception seperately, like display a specific message to the user, you can do it by catching DivideByZero Exception, where as you can't perform the same operation using a generalized exception.

Adding to this, generalized exception can handle all the exceptions but then the message become generic. Here in we want message specific to each type of exceptions.

Related

Distinguish between Exception and Failure in a CATCH block [ RAKU ]

We know that a Failure can be handled by a CATCH block.
In the following example we create an 'AdHoc' Failure (in other-sub) and we handle the Exception in a CATCH block (in my-sub)
sub my-sub {
try {
CATCH {
when X::AdHoc { say 'AdHoc Exception handled here'; .resume }
default {say 'Other Exception'; .resume}
}
my $b = other-sub();
$b.so ?? $b.say !! 'This was a Failure'.say;
}
}
sub other-sub { fail 'Failure_X' }
my-sub();
The output is the following:
AdHoc Exception handled here
This was a Failure
My question is though: How can we distinguish between Failure and a "normal" Exception in the CATCH block in order to differentiate between the two cases?
The relationship between Failure and Exception is that a Failure has an Exception - that is to say, it holds the exception object as part of its state. Something like this:
class Failure {
has Exception $.exception;
# ...
}
When a Failure "explodes", it does so by throwing the Exception that is inside of it. Thus, what reaches the CATCH block is the Exception object, and there's no link back to the enclosing Failure. (In fact, a given Exception object could in principle be held by many Failures.)
Therefore, there's no direct way to detect this. From a design perspective, you probably shouldn't be, and should find a different way to solve your problem. A Failure is just a way to defer the throwing of an exception and allowing for it to be treated as a value; it's not intended that the nature of the underlying problem changes because it's conveyed as a value rather than as an immediate transfer of control flow. Unfortunately, the original goal wasn't stated in the question; you may find it useful to look at control exceptions, but otherwise perhaps post another question about the underlying problem you're trying to solve. There's probably a better way.
For completeness, I'll note that there are indirect ways that one may detect that the Exception was thrown by a Failure. For example, if you obtain the .backtrace of the exception object and look at the top frame's package, it's possible to determine that it comes from the Failure:
sub foo() { fail X::AdHoc.new(message => "foo") }
try {
foo();
CATCH {
note do { no fatal; .backtrace[0].code.package ~~ Failure };
.resume
}
}
However, this is heavily dependent on implementation details that could easily change, so I'd not rely on it.
Just remove the try wrapper:
sub my-sub {
# try { <--- remove this line...
CATCH {
when X::AdHoc { say 'AdHoc Exception handled here'; .resume }
default {say 'Other Exception'; .resume}
}
my $b = other-sub();
$b.so ?? $b.say !! 'This was a Failure'.say;
# } <--- ...and this one
}
sub other-sub { fail 'Failure_X' }
my-sub();
You used try. A try does a few things, but the pertinent thing here is that it tells Raku to immediately promote any Failures in its scope to exceptions -- which is what you say you don't want. So the simplest solution is to just stop doing that.
This answer just verbosely repeats part of jnthn's explanation (see in particular comments he wrote below his answer). But I wasn't convinced all readers would spot/understand this aspect, and didn't think a comment or two on jnthn's answer would help, hence this answer.
I've written this as a community answer to ensure I won't benefit from any upvotes because it obviously doesn't warrant that. If it gets enough downvotes we'll just delete it.

Exception handling- when to use throw keyword with try-catch block

I want to understand how come the below program is running without throw keyword ,when should we use throw with try-catch block.
#include <iostream>
#include <exception>
using namespace std;
int main () {
try{
long double * arr= new long double[1500000000000000000000000000000000000];
cout<<"hello,This is an exception handling program"<<endl;
//throw exception();
}
catch (exception& e){
cout << "Standard exception: " << e.what() << endl;
}
return 0;
}
Output
Standard exception: std::bad_array_new_length
You don't need to throw anything for try catch to work; take a look at these links. Also this question has been asked and answered here many times.
https://msdn.microsoft.com/en-us/library/hh279678.aspx
https://msdn.microsoft.com/en-us/library/6dekhbbc.aspx
The following link will give you a fairly decent explanation.
How to throw a C++ exception
If you actually took the time to go through those you'd have seen that some of the examples show use of a throw while others do not. So back to basics.
try
{
//throw something;
}
catch(...)
{
//do something
}
The above snipet of code represents the following ideas.
If your code can potentially cause an exception, your code should be placed inside of a try block.
The catch portion catches the exception if one occurs.
You will either create your own exception handling class or use someone else's. It's relative to what you're working with.
The idea is quite simple; Try to do this and if it causes an exception catch it and do this so my program doesn't crash.
So, what's a throw and why do I not need one?
A throw statement is you directly throwing an exception. Period end of story. Think about like this. You have a function that divides two numbers, the numbers are based off user input. if the user enters two numbers and one of them is 0 and the other is say 25.
It would cause an exception because of math.... You could then anticipate that and throw that division by zero exception to prevent a fatal crash.
An exception must occur for it to be caught. An exception can be anything you want it to be, and or something you don't want.
What I mean to say is you can throw something that you created that works only with your program.
You asked, why will this code run with out a throw?
A try catch block does not need to have an exception occur. If an exception happens it happens wether you throw it or not. Thus a try catch block does NOT require a throw.
For instance.
try
{
}
catch(...) // This is a real thing. It's meant to catch everything but don't use it becasue it's bad.
{
}
try
{
throw("An exception happened")
}
catch(...)
{
cout << "Nothing actually happened" <<endl; // This block is valid..
}
IMPORTANT: I'm not telling you to not use a throw. I'm simply answering your question and explaining why you don't need one for a try catch to run.

Returning values vs returning error codes?

This is a general programming question, not pertaining to any specific language.
A new programmer typically will write a method that calculates some value, then returns the value:
public Integer doSomething()
{
// Calculate something
return something;
}
public void main()
{
Integer myValue = doSomething();
}
But when an exception occurs during the calculation of something, what is the best way to handle the exception, especially when giving the user feedback? If you do a try/catch of the calculation of something and if an exception is caught, what do you return? Nothing was calculated, so do you return null? And once you return it (whatever it may be), do you need to do another try/catch in the parent method that checks to see if a valid value was returned? And if not, then make sure the user is given some feedback?
I have heard arguments on both sides of the table about never returning values at all, but instead setting calculated values as pointers or global variables and instead returning only error codes from methods, and then (in the parent method) simply handling the error codes accordingly.
Is there a best practice or approach to this? Are there any good resources that one could access to learn more about the best way to handle this?
UPDATE for Clarification
Consider the following code:
public void main()
{
int myValue = getMyValue();
MyUIObject whatever = new MyUIObject();
whatever.displayValue(myValue); // Display the value in the UI or something
}
public Integer getMyValue()
{
try
{
// Calculate some value
} catch (exception e) {
// ??
}
return value;
}
I call the method to get some int value, then I return it. Back in main(), I do something with the value, like show it in the Log in this case. Usually I would display the value in the UI for the user.
Anyways, if an exception is caught in getMyValue(), so does value get returned but it's null? What happens in main() then? Do I have to test if it's a valid value in main() as well?
I need the program to handle the error accordingly and continue. Someone below suggested displaying the appropriate information in the UI from within the getMyValue() method. I see two potential issues:
It seems like I would be mixing the business logic with (in this case) the logic for the UI.
I would have to pass a reference of the MyUIObject to the getMyValue() or something so I could access it from within the function. In the above simple example that is no big deal, but if there is a BUNCH of UI elements that need to be updated or changed based off of what happens in getMyValue(), passing them all might be a bit much...
I've read a bunch about the fundamentals of all of this but I can't seem to find a straight answer for the above situation. I appreciate any help or insight.
I think you do not quite understand exceptions.
If you throw an exception, you do not return from the function normally:
public Integer doSomething()
{
throw new my_exception();
// The following code does NOT get run
return something;
}
public void main()
{
Integer myValue = doSomething();
}
The main advantages of exceptions are:
You can write your code as though everything is succeeding, which is usually clearer
Exceptions are hard to ignore. If an exception is unhandled, typically an obvious and loud error will be given, with a stack trace. This contrasts with error codes, where it is much easier to ignore the error handling than not.
I recommend this post by Eric Lippert, which discusses exceptions and when it is and is not appropriate to handle them.
UPDATE (in response to comment):
You can absolutely handle an exception and continue, you do this by catching the exception.
eg:
try
{
// Perform calculation
}
catch (ExceptionType ex)
{
// A problem of type 'ExceptionType' occurred - you can do whatever you
// want here.
// You could log it to a list, which will be later shown to the user,
// you could set a flag to pop up a dialog box later, etc
}
// The code here will still get run even if ExceptionType was thrown inside
// the try {} block, because we caught and handled that exception.
The nice thing about this is that you know what kind of thing went wrong (from the exception type), as well as details (by looking into the information in ex), so you
hopefully have the information you need to do the right thing.
UPDATE 2 in response to your edit:
You should handle the exception at the layer where you are able to respond in the way you want. For your example, you are correct, you should not be catching the exception so deep down in the code, since you don't have access to the UI, etc and you thus can't really do anything useful.
How about this version of your example code:
public void main()
{
int myValue = -1; // some default value
String error = null; // or however you do it in Java (:
try
{
getMyValue();
}
catch (exception e)
{
error = "Error calculating value. Check your input or something.";
}
if (error != null)
{
// Display the error message to the user, or maybe add it to a list of many
// errors to be displayed later, etc.
// Note: if we are just adding to a list, we could do that in the catch().
}
// Run this code regardless of error - will display default value
// if there was error.
// Alternatively, we could wrap this in an 'else' if we don't want to
// display anything in the case of an error.
MyUIObject whatever = new MyUIObject();
whatever.displayValue(myValue); // Display the value in the UI or something
}
public Integer getMyValue()
{
// Calculate some value, don't worry about exceptions since we can't
// do anything useful at this level.
return value;
}
Exceptions is a property of object oriented languages (OOL). If you use OOL, you should prefer exceptions. It is much better than to return error codes. You can find nice examples how the error-codes approach generates a vastly longer source code than exceptions based code. For example if you want to read a file and do something with it and save in a different format. You can do it in C without exceptions, but your code will be full of if(error)... statements, maybe you will try to use some goto statements, maybe some macros to make it shorter. But also absolutely nontransparent and hard to understand. Also you can often simply forget to test the return value so you don't see the error and program goes on. That's not good. On the other hand if you write in OOL and use exceptions, your source code focuses on "what to do when there is no error", and error handling is in a different place. Just one single error handling code for many possible file errors. The source code is shorter, more clear etc.
I personally would never try to return error codes in object oriented languages. One exception is C++ where the system of exceptions have some limitations.
You wrote:
I have heard arguments on both sides of the table about never returning values at all, but instead setting calculated values as pointers or global variables and instead returning only error codes from methods, and then (in the parent method) simply handling the error codes accordingly.
[EDIT]
Actually, excetion can be seen as error code, which comes along with the relative message, and you as the programmer should know where your exception must be caught, handled and eventually display to the user. As long as you let the exception to propagate (going down in the stack of called functions) no return values are used, so you don't have to care about handling related missed values. Good exception handling is a quite tough issue.
As jwd replied, I don't see the point to raise an exception in a method and then handle the excpetion in the same method just to return an error value. To clarify:
public Integer doSomething(){
try{
throw new my_exception();}
catch{ return err_value;}
}
is pointless.

Using Exceptions exceptionally

This is a refactoring question.
try
{
string line = GetFirstLineFromFile(); //Gets first line from a text file, this line would be a number.
int value = ConvertToInteger(line); // Gets the integer value from the string.
int result = DivideByValue(value); // Divides some number with the value retrieved.
}
catch(Exception ex)
{
}
My main concern is, what is the best approach for exception handling in such situations. Certainly wrapping the whole thing in a single try catch is like saying I expect an exception about everything. There must be some place we catch a generic exception right?
Just don't catch a "generic exception".
How can you possibly handle ANY exception and know how to keep your application in a clean state ?
It hides bugs and it's a really bad idea.
Read this serie of posts on catch (Exception).
You need to think about what exceptions can be thrown from the methods in the try block, as well as which ones of those you can deal with at the current level of abstraction.
In your case, I'd expect that the getFirstLineFromFile methods, for example, can definitely throw exceptions you'd want to catch here. Now whether you wrap and rethrow the exception, or take other action, depends on whether you can actually deal with the exception at this level. Consider the case where you have a default file you can fall back to - the approach may just be to log a warning and continue with the default. Or if the whole application is based on reading a file supplied by the user, then this is more likely to be a fatal exception that should be propagated up to the top level and communicated to the user there.
There's no hard-and-fast rule like "always throw" or "never throw"; in general, I consider that one should throw exceptions whenever there's an exceptional-type situation that is not considered a normal result of the method, and consequently cannot be adequately described by the return type of the method. (For example, an isValidDbUser method returning boolean might be able to handle SQLExceptions as just return false; but a getNumProductsRegisteredInDB returning an int should almost certainly propagate an exception).
Don't listen to the (hordes) of people that will tell you that you should never catch multiple exceptions in one big general block. It's a perfectly reasonable way to do general error handling in some cases, which is why the ability to do so exists in the language.
There will be some exceptions that you can do something specific and useful about (i.e. recover from them in the catch block.) These are the kinds of exceptions that you want to catch individually, and as close to the place where they occur as possible.
But the majority of exceptions that you'll face in real life will be completely unexpected, unchecked exceptions. They are the result of programmer error (bugs), failed assertions, failing hardware, dropped network connections, etc.
You should design your software defensively, by designating specific "chokepoints" to handle these unpredictable exceptions with a minimum of disruption to the rest of the application. (Remember, in many cases, "handling" the exception often just means aborting the current operation and logging an error or otherwise telling the user that an unexpected error occurred.)
So for example, if your program saves a file to the disk, you could wrap the entire save operation in a try block to catch things that goes wrong during the save:
try {
// attempt to perform the save operation
doSave();
} catch (Throwable t) {
// tell the user that the save failed for unexpected reasons
// and log the error somewhere
informUser("save failed!");
log("save failed!", t);
} finally {
// last minute cleanup (happens whether save succeeded or failed)
...
}
Notice that we choose a nice chokepoint method here ( doSave() ) and then stop any unexpected errors from bubbling up any further than this point. The chokepoint represents a single, cancellable operation (a save). While that operation is obviously toast if you're getting an unexpected exception, the rest of the application will remain in a good state regardless of what happens on the other side of the chokepoint.
Also notice that this idiom does NOT stop you from handling some of your exceptions further down in doSave() somewhere. So if there are exceptions that might get thrown that you can recover from, or that you want to handle in a special way, go ahead an do so down in doSave(). But for everything else, you have your chokepoint.
You might even want to set up a general uncaught exception handler for your entire program in your main method:
public static void main(String [] args) {
try {
startApplication();
} catch (Throwable t) {
informUser("unexpected error! quitting application");
log("fatal application error", t);
}
But if you've set your other chokepoints up wisely, no exceptions will ever bubble up this far. If you want to make your general error handling complete, you can also create and assign an UncaughtExceptionHandler to important threads, including your main thread or the AWT thread if you are using Swing.
TL;DR; Don't believe the dogma that you should always catch exceptions as specifically as possible. There are times when you want to catch and handle a specific exception, and other times when you want to use chokepoints to catch and deal with "anything else that might go wrong".

Situations for using exceptions, should user be able to trigger exceptions?

Is it acceptable or sensible to use exceptions to deal with user generated errors? Such as ...
try
{
$job->authorise($user);
}
catch (InsufficentCreditException $e)
{
return E_INSUFFICIENT_CREDIT;
}
catch (PermissionDeniedException $e)
{
return E_PERMISSION_DENIED;
}
or are exceptions reserved for more serious errors only (like file not found, division by zero)?
Bad user input is never an exception. It's the norm!
Seriously though. Exceptions are for exceptional circumstances, and bad/incorrect data from an external source is usually not an exception.
I think that the 'InsufficentCreditException' is a good reason to throw if I understand your use case above. All of the positive flow of the program can be made to process top down, any 'exception' to the positive is a failure and therefore an exception.
Mitch says, 'bad user input is never an exception' and 'bad/incorrect data from an external source is usually not an exception', but if you're under 'program by contract', that is exactly the case. What better reason would there be to throw an exception than invalid data received from an outside source?
One final note, your question and your use case don't match. Insufficient Credit is not usually caused by user generated error. A clear case of cause/effect would make this easier to answer.