Best way to Handle Exceptions in C# Catch Block - exception

Best way to Handle Exceptions in C# Catch Block.I have no other choice but to Log the error to SQL DB in Catch block.Howver i am wondering what is the best way to catch exception if caught in Catch block itself?

I would create a separate class to handle error reporting, and expose a function to handle logging the error in the DB.
I found this guide useful:
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
Some code that I have used in the past looks like:
try{
throw;
}
catch(Exception ex){
LoggingClass.LogError(some paramaters,ex.tostring());
}
and then your logging class could look like
public static class LoggingClass {
public static void LogError(some paramaters, ex.tostring()){
//try to log to database
//catch and report error in some other way
}
}
I used this article as a reference in the past because I liked the idea of logging to a text file (in the event of a DB error) and then displaying a "nice" message to the user.
C# best practice error handling and passing error messages

Related

Difference between throwing Exception and throwing a specific Exception such as NullPointerException

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.

Exception Thrown From Service Not Being Caught in Controller

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.

ejb-3.0 customized exception

My ejb3 application running on JBOSS6 already has a customized Exception handler "Ejbexception.java" which extends Exception class
I want to use the same to trap Exceptions with some number and send back the same to the Client Code for handling gentel message .
ex:
try{
.....
}catch(SQLException ex){
throw new EjbException("1001");
}
Now HOWto get the "1001" on the Client Code ?????
thx in advance
karthik
Did you write this Ejbexception class yourself? If so, that's a poor choice of name, because there's already a javax.ejb.EJBException in the library. However, it will work: when you throw it, the container will transport it to the client, who can then catch it. The string you inserted will be available from the exception's getMessage() method, just like normal.
If you're actually throwing a javax.ejb.EJBException here, then things are slightly different. That exception is aimed at the container, not the client. I actually don't know how it's made visible to the client. My suggestion would be to switch to using a custom exception, which the container will then pass to the client.

Multiple try-catch or one?

Normally, I'd do this:
try
{
code
code that might throw an anticipated exception you want to handle
code
code that might throw an anticipated exception you want to handle
code
}
catch
{
}
Are there any benefits to doing it this way?
code
try
{
code that might throw an anticipated exception you want to handle
}
catch
{
}
code
try
{
code that might throw an anticipated exception you want to handle
}
catch
{
}
code
Update:
I originally asked this question w/reference to C#, but as A. Levy commented, it could apply to any exception handling language, so I made the tags reflect that.
It depends. If you want to provide special handling for specific errors then use multiple catch blocks:
try
{
// code that throws an exception
// this line won't execute
}
catch (StackOverflowException ex)
{
// special handling for StackOverflowException
}
catch (Exception ex)
{
// all others
}
If, however, the intent is to handle an exception and continue executing, place the code in separate try-catch blocks:
try
{
// code that throws an exception
}
catch (Exception ex)
{
// handle
}
try
{
// this code will execute unless the previous catch block
// throws an exception (re-throw or new exception)
}
catch (Exception ex)
{
// handle
}
If I could choose the second I would probably separate this into two functions.
Neither, just use multiple catch blocks for specific exceptions (unless there is just a ton of code in the block and only a couple of lines may throw an exception.In that case I would go with the second method).
You're thinking about this the wrong way. What do you need to do in your catch blocks? If you would recover from any of the possible exceptions by running the same code, no matter which operation threw the exception, then use one catch block. If you need to do different clean-up operations depending on which operation threw, then use multiple catch blocks.
Also, if you can use try/finally or the RAII pattern instead of try/catch, then you should.
Second method is better in my opinion because it allows you to trap errors with more accuracy.
Also wrapping your entire code inside one big try/catch block is bad, if your app has some sort of problem and it crashes but since you trapped a big generic execption the chance that you can actualy handle it correctly is lower.
You should have spesfic parts inside try catch, like if your reading a file or taking user input. That way you can better handle that exeception
There are time we want to show specific error to user.
try{
try{
... send message
}
catch(exception e){
...log error
...rethrow send related error/show custom error
}
try{
...try to receive response
}
catch(exception e){
...show receive related error
}
//finally close the connection
}finally{
...close connection
}
I prefer the second method - it makes debugging easier, error handling more accurate and also feeds nicely into your unit testing nicely too.
I would go for the 2nd option, but whenever I see this code pattern my first feeling is to think about splitting it into multiple functions/methods. Obviously whether to do so depends on what the code is doing ;)
It depends on the nature of the type of errors happen in your code.
If the handling of those errors you are going to do is same go for single try ... catch for that group of code. Else it will be too tedious.
If the errors required different handling, separate it because you have to.
DO NOT APPLY A SINGLE METHOD FOR ALL CASES. PROGRAMMING MOST OF THE TIME IS CONTEXT SPECIFIC :)
You need to reach a balance of "GOOD/COMPLEX" and "BAD/SIMPLE". The more you code, you will be less stuck in this kind of dilemma :)
Happy programming!
Second method. Keeping the code that might throw an exception separate from other code - keeps the section smaller and easier to manage instead of wrapping all code, even that which will not throw exceptions.
2nd way but ideally use code guards - try/catch can be costly, if you catch an exception.

Implication of (not) rethrowing exception after logging

In a team environment, if I handle an exception (like so):
protected void Page_Load(object sender, EventArgs e)
{
this.exTest();
}
public void exTest()
{
try
{
throw new Exception("sjsj");
}
catch (Exception ex)
{
string s = ex.Message;
throw;
}
}
What is the implication of not rethrowing the exception (throw)? Even without the keyword the custom error settings in web.config are used (redirection to specified page).
Thanks
If you don't rethrow the exception, the calling code will presumably assume that the method worked. That's usually a really, really bad thing to do.
"No, I didn't manage to load your account details fully, so your bank account has the default balance of 0. Now, wait while I just write that data back into the database... In the meantime, feel free to peruse the log I helpfully generated to show just why I'm screwing up your data" ;)
Seriously, logging an error isn't equivalent to handling it. You should rethrow an exception unless you've actually handled it to such an extent that the caller can effectively assume it didn't happen.
If your error page is being shown anyway, that would suggest that even after this method failed, another one failed as well. You shouldn't rely on that though.
The consequence of not rethrowing the exception is that you effectively ignore the exception. This is rarely the right thing to do as it masks errors. Ignoring errors could put your application in not well defined state with all sorts of strange side effects. In short: Don't go there!