What guidlines do you use when deciding whether to let a method dodge an exception (ie: let the exception propogate up) or handle it once the exception is recieved?
Here is an example of what I am trying to ask
If I have three methods method1,2,3 and 3. Method1 calls Method2 which Calls Method3. and the exception is only thrown in method 3 when should I let the exception propogate upward as follows (excuse my pseudo java ;) )
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
And when should I handle the exception once it is raised as follows
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
try {
call readFille
} catch (exception e) {
doErrorProcessing;
}
}
The rule I follow:
If I can fix an exception, or nullify the problem that caused it (sometimes this means just ignoring it altogether), I'll handle it. Otherwise it gets passed up to the next level.
And I always try to fix exceptions as low in the tree as possible (i.e. as soon as possible after they occur) - this localizes exception handling and avoids big honkin' exception handlers in your upper levels.
Like all answers in software, this one for me is "it depends".
Most exceptions should be, in fact, exceptional, so generally I tend to like them to break the app when they occur. If the exception represents some recoverable error condition, then it should be handled at the point in the call stack when you have the information you need to do so safely. This would include situations where the error can be corrected by the user, i.e. catching the exception to report it back to the user so that they can take appropriate actions.
If the lower level routine knows what to do about the exceptional condition, it should probably handle it. If it is an exceptional condition unrelated to the task that function is intended to perform, it would probably make more sense to let it be handled at a higher level.
Only catch exceptions you can handle. Let everything else pass you by.
From a Java point of view, I always try and use unchecked exceptions to avoid adding the throws declarations in the method signatures.
Then where I actually catch the exception will be depending on the situation. I'd always want to handle the exception as high in the chain as possible where the exception is applicable. And if it's a system level exception where you expect the application to fall over, then I might have an exception handling mechanism where it will "catch all".
Related
I am wondering what is the difference between throwing just Exception and throwing a specific Exception such as NullPointer Exception.
To my current knowledge an Exception should be able to catch any type of exception where as using a specific Exception expects that only that exception type can be thrown.
Example:
void test(String testString) throws Exception;
vs
void test(String testString) throws NullPointerException;
If this is correct than to me it makes sense to just always throw Exception and to never name a specific exception. Am I missing something important here? Does it at the very least effect performance at all? A lot of people are looking between throwing and catching exceptions but nobody asks this very basic question.
I do not see a benefit of throwing any exception except Exception.
To start off, Exception is a base type of every Exception. Just like object is for everything.
By throwing a specific Exception you provide more information to the consumer of what has happened.
Imagine scenario where you get a plain Exception without a message, consumer is lost. When for example framework throws a NullReferenceException, then you are aware of a fact that one of your objects does not have a reference which it was trying to access.
This is how you can chain exceptions and make use of their types:
try
{
throw new NotImplementedException();
}
catch(NullReferenceException ex)
{
// Logic for NullReference exception if needed.
}
catch(NotImplementedException ex)
{
// This will be executed.
}
catch(Exception ex)
{
// Will catch every exception.
}
There are at least two reasons why you would want to throw a specific kind of exception:
If a program fails with an exception, you will have more information with which to determine what went wrong. Compare seeing Exception with FileNotFoundException. The latter clearly gives you more information.
In some cases, the code will want to catch certain kinds of exceptions. For example, when working with serial ports, you might want to catch and handle a TimeoutException differently from a NullReferenceException.
The NullPointerException you mentioned is a very good example from the regular Exception because it is a subclass of RuntimeException. Any throwing of (a subclass of) RuntimeException does not have to be caught or declared.
Any other (=not a subclass of RuntimeException) Exception has to be handled in your code by either a try/catch block or a throws declaration. Otherwise, your code will not even compile! That forces you as a developer to handle errors that might pop up.
As for why using different Exception types is useful, consider the following simple example that uses multiple catch statements:
void doDBStuff(){
try {
performStatement(someStatement);
} catch(SQLException e){
//invalid SQL syntax, something is broken
} catch(AuthenticationException e){
//invalid user credentials for the db, inform the user to change these values
}
In this example, two different exceptions end up in two different catch blocks which lets you handle these errors differently.
It's a best practice to throw specific exceptions, instead of a generic one. This is because the caller might want to treat the exceptions differently, for example in a WebApi you might want to return a Bad Request response (400) for a ArgumentNullException, but you might want to return a different result for other types of exceptions. For example you might actually throw a custom NotFoundException and then the controller would catch it and return a Not Found response (404) instead.
Basically if you throw specific exceptions you are allowing the consumer code to handle the different exception scenarios the way they want.
In my Grails service I have code like the following:
def createCharge(chargeParams) {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw e
}
}
From my controller I do the following:
try {
service.createCharge(chargeParams)
} catch(CardException e) {
}
However, my controller is not catching the re-throwing of the CardException. If I wrap CardException in a RuntimeException via:
throw new RuntimeException(e)
and/or remove the signature from the catch to just catch(e) without typing it, it works, but I lose some information from the exception, like the message.
As a note, CardException is an Exception, not a RuntimeException. I'm not sure if that matters.
Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException. So this:
def createCharge(chargeParams) {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw e
}
}
is effectively the same as:
def createCharge(chargeParams) throws UndeclaredThrowableException {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw new UndeclaredThrowableException(e)
}
}
the exception thrown by the above, obviously wouldn't be caught by:
try {
service.createCharge(chargeParams)
} catch(CardException e) {
}
But it will be caught by:
try {
service.createCharge(chargeParams)
} catch(e) {
}
Because this is just a shorthand for:
try {
service.createCharge(chargeParams)
} catch(Exception e) {
}
Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException.
You seem to imply that Groovy wraps checked Exceptions by a UndeclaredThrowableException, this is not the case. If a Grails Service throws a unchecked Exception the Exception is eventually wrappped by an UndeclaredThrowableException but this is a java.lang.reflection mechanism and will only occur when a proxy class is involved.
This happens to be the case because a Grails Service is involved. I'm not sure how many proxy classes are exactly involved by there is at least one: a class that does the transaction handling (by Spring).
The class will wrap any method in the Service with a transaction and rollback the transaction when a RuntimeException occurs. Spring transaction management by default doesn't rollback in case of a checked Exception.
Java
This makes sense in plain old java, since the developer will see the Exception in the application code and will be warned to do something about it. If the developer is smart he will deal with any Exceptions during the scope of a transaction. If he doesn't rollback the transaction he is basically saying: “In this situation, the data integrity provided by the transaction is not important to me. I will recover from this error in some other way”
Groovy
This doesn't make sense in a Groovy world because the Groovy compiler doesn't enforce the dealing with Exceptions. It in effect treats Exceptions exactly the same way as RuntimeExceptions.
There is however a caveat: The reflection mechanism sees an Exception thrown by the proxy that is not in the method signature of the original Service. This is possible because:
Groovy doesn't enforce handling the Exceptions
A proxy method can always throw any Throwable (check InvocationHandler JavaDoc)
Because the reflection mechanism used is from Java, it must conform to the Java rules. So it will have to wrap the Exception in a RuntimeException,.. in this case a UndeclaredThrowableException.
Grails
Now it gets really tricky because if you call your Service method from a Controller and an Exception occurs. You will see a RuntimeException bubble up (because of some hidden mechanism) but your transaction will not be rolled back (because of some hidden mechanism).
This behaviour is very dangerous as the developer really has to remember to properly deal with any Exceptions (which the compiler will not help with) or the developer has to make sure that any Service is properly instructed with #Transactional(rollbackFor = Throwable).
This is a design issue that I think the developers of Grails have overlooked when they first designed this. But I think the default behaviour is so wrong and so dangerous this should really be changed.
I think the simple solution to the problem is to add a throws CardException statement to the service method, thus the exception will no longer be wrapped in UndeclaredThrowableException and the controller will catch the proper exception type.
Just catch the UndeclaredThrowableException, get the message from it, and then re-throw if need be.
catch (UndeclaredThrowableException e) {
def s = e.getUndeclaredThrowable().getMessage()
// do something with the message
throw e
}
The above code fragment will just catch the exception you've explicitly thrown in the code (eg CardException). For example a NullPointerException will not be caught and bubble up.
Consider a method() that throws some exception in its body.
Consider the following scenarios:
Scenario 1:
{
//..
// ..
method(); //Exception handled inside the method
//..
//..
}
In this case the exception should be handled within the method() itself.
Also consider this:
Scenario 2:
{
//..
//..
try{
method(); //Exception not handled with-in the method
}
catch(){}
//..
// ..
}
Why a situation like scenario 2 is not allowed? ie why it is forced that the exception should be handled within the method?
You can add throws clause to your method and make it throw an exception, which can be handled, as mentioned in Situation 2. So its allowed, like this:-
void method() throws Exception{
}
Both scenarios are allowed. The restriction (if that's the right term) that Java imposes is that the exception must be handled somewhere.
In the first scenario, the called method handles the exception itself - so there's no need for the try-catch in the calling method.
The second scenario is valid - but only if method() includes the throws declaration to indicate that the exception must be handled somewhere else.
void method() throws Exception
{
}
It is allowed!
use as follows
public void method() throws ClassNotFoundException {
to catch a ClassNotFoundException.
(In most cases you should not throw a bare Exception, like other posters simplified)
Whether to chatch inside or outside is software design. There is no rule of thumb.
My experience is that catching outside leads to less complex code, which can be better unit tested .
Look for design pattern "last line of defense":
That means that in your top most class e.g in main() there is a catch (Exception ex) {
which catches when no other method catched it. in that case you can log the exception and (try to) safely shut down your system. This is the last line of defense.
Note: spmetimes it also makes sense to catch(Throweable th),
If you handle exception using senario-2, then cannot map the exception to the actual one. i.e you cannot state it as per the code in block. So please handle the exception to the spot itself, so that you can specifically explain why the exception has occurred.
As said above, the idea is to throw early and catch late. Overall, you want to minimize exceptions you throw by simply making your logic "flow". But there are always situations which are tricky to handle, or obfuscate code too much, so it is worth ensuring the user understands the risks of using certain methods and handles them accordingly.
TL;DR: Never trap InterruptedException unless you really mean to. It almost always needs to be thrown.
This great question is actually a very important design decision. Getting this right is difficult and getting this right across an entire team is even more difficult. The answer to the question lies within your implementation. Does the error need to be immediately shown to the user? Do you have an auxiliary method to recover from the failure? Is the exception a fatal event?
Please do yourself a favor and never write an empty exception handler. You will be very happy to have put in a log.debug statement in there when things go awry. Other than that: learn what every exception means and respond to it in the most graceful way possible.
From what I understand throw causes an exception.
It looks like it can be used to test your catch exception.
What are the benefits/uses for it? Why would you want to purposely cause an exception?
Why use throw in catch? Seems like it catches the exception just to cause an exception again.
try
{
//blah
}
catch
{
throw;
}
throw; rethrows the current exception. It's used for when you want to catch an exception and do some handling of your own, but otherwise still want the exception to propagate more-or-less as if you never caught it.
The difference (in languages that let you just say throw;, like C#) is that when you rethrow an exception, the original stack trace remains mostly intact. (It includes the line where you rethrew the exception rather than the line where the exception occurred in the corresponding try block, but otherwise the whole stack trace is preserved.) If you say throw the_exception_you_caught;, it's usually treated as if you threw a brand new exception from right there -- the existing stack trace gets obliterated and a new one starts from that point.
Exceptions are mechanism for error handling. For instance, you may throw an exception to indicate that a webservice call has timed out, or bad input as been provided to a method. The idea is that calling code knows how to deal with these exceptions and handles them gracefully — perhaps fixing what's wrong in the case of bad input (by prompting the user) or by trying a callout a second time.
A catch block is where you do your handling of the error, and in certain scenarios you may want to do some local cleanup in the method running, but then you still need to report the error to calling methods, so you throw the exception once more (or throw a different, maybe more generic or specific exception) which you then handle in your calling code.
Description
You can do this to, for example, log something and give the exception back to the calling method / assembly.
You can handle the exception and signals the caller that a exception is happend instead of return a boolean that indicates if the method has success.
This is useful for unit tests and more.
Sample
try
{
//blah
}
catch
{
// log exception to textfile of database
throw;
}
This is a common pattern in .Net code. It's used when the caller wants to either log, wrap or react to an exception and then pass it back up to the caller. For example
try {
SomeFunction();
} catch {
CloseMyResource();
throw;
}
The advantage of throw vs throw exceptionVariable is that throw preserves the original stack trace. The next person to catch the exception sees the original stack trace. This is essentially for tracking down errors in deep call stacks.
I think it may be better to think of a throw as your informed reaction to an exception in your code rather than the cause. Semantics I know but it helps.
You throw a different exception in a catch to add information. Your converting what may be a generic OS exception into one meaningful to your application. e.g. Out of memory exception may be caught and a new exception with the out of memory as the inner exception be throw saying something like "Error while computing the answer to life the universe and everything". More useful that just an out of memory exception.
You may use a 'throw' on its own as a rethrow. The catch allows you to do something before rethrowing. If we are talking C# check out 'finally'.
When something really bad happens, that ought not happen, then you can abort and inform the caller by throwing an exception. It means that you do not need to have every method returning result codes and every caller testing fault/success codes. It also nicely abstracts who handles such 'exceptions' or even if you just leave it to the OS.
Quick answer ... it makes your code simpler and gives you better control of aborting and handling exceptions. Think of it as a messaging/abort system.
You would re-throw the same exception if you wanted to do some logging here or some clean up but would like to still have the calling functions further up the call stack to have to handle that same exception.
A more typical use would be:
try {
// ...
} catch (EmailException ex) {
SMS.AlertError("Email is not working", ex);
throw;
}
If you throw ex you will have stripped out information such as the call stack from the exception.
The some function above that would:
try {
// ...
} catch (Exception ex) {
WorkFlowProblems.Add(new OrderNotSentException("Email did not work", ex));
View.ShowError("Could not send order!");
}
Here you make a new exception and set it's "inner exception" to be original cause. This is a good way for multi-part systems to have the right level of information about what went wrong and at what level.
Doing this preserves the stack trace. In your example, it's not useful, however, you could catch the exception, log it and then rethrow so that the exception bubbles up to be handled by code higher up.
The place where throwing exception (in my opinion) is MOST useful is when you want to create an instance of a new object and there's some possibility that the instance needs to fail in creation, in which case the instance can be made to remain null (since constructors don't "return" anything... so for example...
Foo foo = new Foo();//
//at this line foo may or may not be the exact thing you want it to be, depending on whatever conditions made the creation of Foo possible.
So, Foo throws an exception you can do this:
Foo foo = null;
try{
foo = new Foo();
}catch(FooException fe){
//here you can find out if Foo didn't get instantiated as you wanted it to
}
//and here you can test if foo is still null.
My technical lead insists on this exception mechanism:
try
{
DoSth();
}
catch (OurException)
{
throw;
}
catch (Exception ex)
{
Util.Log(ex.Message, "1242"); // 1242 is unique to this catch block
throw new OurException(ex);
}
1242 here is an identifier of the catch method which we handle an exception other than OurException. Every catch block in the project must have a unique identifier so we can know where the exception occurred by looking at the logs.
For every method, we have to catch OurException and throw it. If an other type of exception is thrown, we have to log it and mask it by OurException before rethrowing it.
Is this a reasonable approach? If there are any, what are the better alternatives?
Edit: I've been told the stack trace does not produce meaningful results in release mode.
Are you suggesting catching and throwing generic exceptions is OK?
Edit2: Thank you all. I used your answers as part of my argument against this but I've been told you are not experienced enough and do not know how to deal with real life situations. I have to go this way.
You can also look into the Exception Handling Application block.
I have used it in a few projects and it is very useful. Especially if you want to later change how your exception handling works, and what information to capture.
I would think that using the stack trace would be much more intuitive than any identifier.
As far as the custom exception, why not do this?
try
{
DoSth();
}
catch(Exception ex)
{
Util.Log(ex.Message, ex.StackTrace);
if(ex is OurException) throw ex;
else throw new OurException(ex); // use the original exception as the InnerException
}
Also, I'm not sure why you'd want to rethrow an exception after it's been handled - can you explain the reasoning behind that?
#Ali A - A very valid point, so allow me to rephrase - why rethrow the exception instead of finishing the handling of it right here?
EDIT:
Instead of rethrowing, why not do this?
try
{
DoSth();
}
catch(Exception ex)
{
Util.HandleException(ex);
}
Util.HandleException:
public static void HandleException(ex)
{
Util.Log(ex); // Util.Log should log the message and stack trace of the passed exception as well as any InnerExceptions - remember, than can be several nested InnerExceptions.
// Any additional handling logic, such as exiting the application, or showing the user an error message (or redirecting in a web app)
}
That way, you know every exception only gets logged once, and you're not throwing them back into the wild to wreak any additional havoc.
Having the OurException is kinda weird. Usually, you want to have specialized catch blocks and then the last one, the one that catches a generic Exception is where you do your logging:
try
{
DoSomething();
}
catch (DivideByZeroException)
{
// handle it here, maybe rethrow it, whatever
}
// more catch blocks
catch (Exception)
{
// oops, this is unexpected, so lets log it
}
But what your doing will work. I do believe the 1242 should go though. Here's a method to print the method, filename, and line number you could use instead. I haven't tried it myself but it looks good:
[Conditional("DEBUG")]
public static void DebugPrintTrace()
{
StackTrace st = new StackTrace(true);
StackFrame sf = st.GetFrame(1); // this gets the caller's frame, not this one
Console.WriteLine("Trace "
+ sf.GetMethod().Name + " "
+ sf.GetFileName() + ":"
+ sf.GetFileLineNumber() + "\n");
}
I have two types of exceptions: repairable exception and fatal exception. If some object throw repairable exception, this is mean that error occur but object is not damaged and can be used over again. If some object throw fatal exception, this is means that object state is damaged, and any attempt to use object will lead with new error.
Update: all exceptions might be handled as soon as possible, and as close to error source as possible. For example, if object, stored in collection throws the fatal exception, exception handler just remove this object from collection and delete it, not all entire collection of objects.
From what I understand, the purpose of exceptions are to propagate unexpected errors. If you catch it close enough to the method that throws it, you are more in the context of how to handle it.
Your example is to catch an unexpected error, and rethrow that up the chain. This is not handling the exception, but wrapping it into your own.
But your wrapping does not seem to add any more value to the exception, but might even clutter things.
An extreme example:
void a() {
try {
c();
} catch(MyException1 ex) {
throw;
} catch(Exception ex) {
log(ex);
throw new MyException1(ex);
}
}
void b() {
try {
a();
} catch(MyException2 ex) {
throw;
} catch(Exception ex) {
log(ex);
throw new MyException2(ex);
}
}
Notice how that, in the earlier example, the original exception is logged twice. And it is wrapped in two exceptions.
When you log the same exception a few times it becomes harder to trace (since the log file grows rather big).
Of course this might be an extreme example, but I find it hard to believe that your entire application has only one type of exception in use. It does not describe sufficient all the different types of errors that might happen.
I personally prefer to log the exception only at the catch block where I handle it. Anywhere else might just create duplicated logging.
I think that having a hard coded number on the throw line is not a good practice, how do you know whether that number is being used or not?, or, which is the next error number to throw? Maybe you can have, at least, listed on an enum... not sure.
Everything looks right except for that weird number.
The stack trace will contain the information you need.
Seems to me that the stacktrace is a better way to handle this. What happens if you mistakenly reuse a number?
As far as whether this is a good idea or not, in the absence of any more information, I'd tend to say no. If every method invocation is wrapped in a try/catch block it will be very expensive. Generally, exceptions fall in to two camps -- those you can reasonably expect and deal with and those that are really bugs (or at least not successfully anticipated). Using a shotgun approach to catching all exceptions seems to me like it just might do more to hide the latter than help get them resolved. This would be especially true if at the top level you caught all exceptions so that the only record you have is the log message.
I fail to see how this is helpful. You can already know where the exception came from with the stack trace, and you are adding an unnecessary level of complication.
The drawbacks:
That number doesn´t inspire much confidence, stack trace is much better
Why have 2 catch blocks if your custom exception can be handled on the "catch(Exception ex)
"?
I think this is a bad pattern, because you have the information about the whole call stack readily available in the exception, there is no need to pseudo-handle the exception by logging and rethrowing it. Only catch an exception at a place where you really can do something about the problem.
Logging the stacktrace would be a lot better than the hardcoded number. The number tells you nothing about what routine called this one.
Also the number is a pain to manage, and error-prone at that.
edit: it is true that the stacktrace doesn't always produce meaningful results in release mode, but I think the same can be said of this hardcoded number scheme! :-)
With the language you're using, does the compiler provide macros with the current filename and line number? That would be better than trying to roll a unique number yourself. And, if you can't do that automatically, do it manually, or come up with some scheme to guarantee uniqueness that doesn't require some central allocation of numbers!
My application is built in release mode, and i use the Exception Handling Application Block, so i never have any catch ex blocks of code, it is caught by the EHAB, this itself writes to a log file with all the info i need; stack trace etc, time, etc.
the only problem with this is if someone has put
catch ex
{
//do stuff
throw ex;
}
as this will wipe out the stack trace.