I am in situation where I need to find the best possible approach to do this,
try
{
// Service call.
}
catch (FaultException exception)
{
service.Abort();
throw new FaultException(Resources.UnexpectedErrorOccurredAtServer, exception);
}
Or
catch (FaultException exception)
{
service.Abort();
throw new Exception(Resources.UnexpectedErrorOccurredAtServer, exception);
}
// Caller.
Main()
{
try
{
serviceCaller()
}
catch(FaultException ex)
{
// Should we have this catch???
}
catch( Exception ex)
{
// Handle unexpected errors.
}
what will be the best approach to throw the expected exception to caller.
If we throw FaultException caller main method should Handle it explicitly or general exception will work.
The best approach would be
try
{
// ...
}
catch (FaultException ex)
{
service.Abort();
throw;
}
This preserves the stack trace, which your proposed methods do not. See Throwing Exceptions best practices.
You may be interested to check WCF error handling and some best practices
The best approach would be like this:-
try
{
proxy.SomeOperation();
}
catch (FaultException<MyFaultInfo> ex)
{
// only if a fault contract was specified
}
catch (FaultException ex)
{
// any other faults
}
catch (CommunicationException ex)
{
// any communication errors?
}
Related
I have to do a code review and i got to a code part that addresses possibles exceptions. it looks to me that the developer coding works but i want to ask what is the usual and correct way to do that. What is the best way to do catch exceptions?
the coder wrote:
try
{ . . . }
catch (Exception ex)
{
if (ex is PlatformNotSupportedException)
{ //for the Windows version or edition that does not support.
// tracing
}
else if (ex is NotSupportedException || ex is IOException)
{ // for the NTFS not supported or EFS is not configured
// tracing
}
else
{
//report any exception as encrypt/decrypt
}
}
I thought that the book says that it should be:
catch (PlatformNotSupportedException pnse)
{
//for the Windows version or edition that does not support.
// tracing
}
catch (NotSupportedException nse)
{
// for the NTFS not supported or EFS is not configured
// tracing
}
catch (IOException ioe)
{
// tracing for IOE
}
catch (Exception e)
{
//report any exception as encrypt/decrypt
}
The second approach would be more preferred. However, there is tiny difference between proposed solution and current one. You'd need to refactor to a method, or copy the code in two places (NotSupportedException and IOException catch blocks), whilst current implementation handles it under the same if block.
So, if you want to follow the same approach, you can use when keyword to filter out certain types and more.
catch (PlatformNotSupportedException pnse)
{
// for the Windows version or edition that does not support.
// tracing
}
catch (Exception ex) when (ex is NotSupportedException || ex is IOException)
{
// for the NTFS not supported or EFS is not configured
// tracing
}
catch (Exception e)
{
//report any exception as encrypt/decrypt
}
If that's not mandatory, you can leave implementation as is
TLDR: Use the second form so that the compiler catches ordering errors.
The reason that you should use the second form is because then you will get a compile error if you attempt to handle the types in the wrong order.
For example, this will give you an actual compiler error:
try
{
throw new ArgumentOutOfRangeException();
}
catch (Exception)
{
Console.WriteLine("Caught 'Exception'");
}
// This gives a compile error:
// "Error CS0160 A previous catch clause already catches all exceptions of this or of a super type ('Exception')"
catch (SystemException)
{
Console.WriteLine("Caught 'SystemException'");
}
However, using if/else if will NOT cause a compile error, so the error goes unnoticed:
try
{
throw new ArgumentOutOfRangeException();
}
catch (Exception ex)
{
if (ex is Exception)
{
Console.WriteLine("Caught 'Exception'");
}
else if (ex is SystemException) // This will never be reached, but no compile error.
{
Console.WriteLine("Caught 'SystemException'");
}
}
Note, however, that tools such as Resharper will warn you for the second case.
this would be generic for all type of exception
try
{
.....code
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
What is difference between these types of catch, except that in first I can use e?
catch (Exception e)
{
//some code;
}
catch (Exception)
{
//some code;
}
catch
{
//some code;
}
try{
//do something
}catch{
//do something
}
This catch is executed, regardless of the exception.
try{
//do something
}catch (Exception) {
//do something
}
This catch is executed when a specific Exception is thrown
try{
//do something
}catch (Exception e) {
//do something
}
Same here, only that you have a reference to the Exception. That way, you have access to it.
Read more here.
Catch can catch different exception's types.
When you use the syntax catch(Exception) you are telling the compiler to write code that catches any kind of exceptions while, if you use a syntax like catch(InvalidOperationException), you are asking to catch a specific type of exception
To simplify things you can write catch without any type and this has the same meaning of catch(Exception)
try
{
// Uncomment this line to catch the generic exception
// throw new Exception("An exception occurred");
throw new InvalidOperationException("Operation x is not valid in this context");
}
// Comment the following lines to fall into the generic catch exception
catch (InvalidOperationException)
{
// But without the variable we cannot print out the message....
Console.WriteLine("An invalid operation has been catched");
}
catch (Exception)
{
Console.WriteLine("An exception raised");
}
You cannot use the syntax catch(Exception ex) in the same try catch where you don't specify the name of the variable for the same type of exception.
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// Syntax error: CS0160: A previous catch clause already catches ......
catch (Exception)
{
Console.WriteLine("An exception raised");
}
Strangely enough this doesn't result in a syntax error, but in a simple warning
catch(Exception)
{
....
}
// Warning CS1058: A previous catch clause already catches ......
catch
{
....
}
Of course you shouldn't catch exceptions that you are not prepared to handle. If you do it just to expose a message you risk the correct functionality of your program. Usually you catch only specific exceptions that you are know how to handle to allow your program to continue. The only reason that I could find to catch all exceptions is when you write down the exception data in some kind of log file and then throw again the exception.
catch(Exception ex)
{
Logger.Error("Unexpected exception", ex);
throw; // NEVER throw ex;
}
Remember that it is really never required to write throw ex because you loose the stack trace of the exception and make very difficult to track down the exact error point.
See: Best practices for catching and re-throwing .NET exceptions
If your code throws an exception, then the catch Block will be thrown and you have access to it over e.
catch (Exception e)
{
//some code;
}
If your code throws an exception, then the catch Block will be thrown indepented from the exception type and you don’t have access to it.
catch
{
//some code;
}
If your code throws an exception, then the catch Block will be thrown depending from the exception type and you don’t have access to it.
catch (Exception)
{
//some code;
}
Instead of Exception you should use a more specific exception type!
let's check
in this code you can write e.Message for check Catch Message
catch (Exception e)
{
Console.WriteLine("Error Message is : " + e.Message);
}
but in this you just skip From Exception (All Exceptions) and you can add more Exceptions
catch (sqlExcetion)
{
//if your code have sqlEsception Get here
}
catch (Exception)
{
//if your code have any Exception Get here
}
and in this code you can create one catch and all catch go this
catch
{
//all catch get here
}
The minor difference between:
try{
//do something
}catch (Exception) {
//do something
}
and
try{
//do something
}catch (Exception e) {
//do something
}
is: (the second one will give)
The variable 'e' is declared but never used
Also, if the code is like this:
catch(Exception e) { throw e; }
the original stacktrace is gone. So, you have to do: catch(Exception e) { throw; }
to see the original stacktrace.
I am trying to catch the InvalidOperationException that can sometimes occur when declaring variables. The following code doesn't work however. Probably because I don't really know how you catch an exception.
public override void Download()
{
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException exception)
{
return;
}
catch (Exception exception)
{
throw;
}
}
}
Any help at all would be very appreciated.
You don't need to throw the exception yourself. Just have:
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
}
catch (InvalidOperationException exception)
{
// Error logging, post processing etc.
return;
}
You shouldn't really be catching the general exception either unless you have a really good reason to - i.e. your application cannot crash, but if you do you need to be able to recover from it.
Let us say we have an external server which we use (e.g.-telephony station, etc.). Also we have the next code:
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
throw;
}
Theoretically UpdateCallState could throw but we would hide this exception using that code and would treat only exceptions generated by CreateCall in a right way.
The question is, what is the right pattern for these situations so that we treat all the exceptions correctly?
You can always nest another try..catch inside the first catch and deal with it appropriately.
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
try
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch(Exception updateEx)
{
// do something here, don't just swallow the exception
}
throw; // this still rethrows the original exception
}
Break it up. Something like
if !TryCreateExternalCall(callParams)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
else
{
throw new ExternalServiceException(???);
}
TryCreateExternalCall should of course log the exception and stacktrace, before it swallows and returns false.
It is not a good practice to throw exception in Catch block.
The try, Catch suggest that
try
{
//make some changes. If something goes wrong go to Catch.
}
Catch(exception)
{
//I will clean the mess. Rollback the changes.
}
Catch the exception, only if you can handle the exception. Else bubble it up let the caller decide on what to do with the exception.
You should catch the most specific exception first, followed by the most general exceptions.
try
{
externalService.CreateCall(callParams);
}
catch (CreateCallExceptionType ccEx)
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch (Exception ex)
{
//do something
}
And then you could handle the UpdateCallState exception within the method.
If I have some code inside a big try catch which eventually catches an OracleException and a general Exception then I can't throw any custom exception inside the try catch can I, as it gets caught by the general Exception.
What am I supposed to do in this instance?
Thanks
try
{
// some code
if(a==b)
{
throw new MyCustomException(ex);
}
}
catch(OracleException ex)
{
...
}
catch(Exception ex)
{
...
}
Do you mean that you want to throw a custom exception that isn't caught by the catch-all Exception block?
If this is the case, then try this:
try
{
throw new MyCustomException();
}
catch (OracleException ex)
{
// Handle me...
}
catch (MyCustomException)
{
// Important: NOT `throw ex` (to preserve the stack trace)
throw;
}
catch (Exception ex)
{
// Handle me...
}
Any exception of type MyCustomException will be caught by the second catch (rather than by the 3rd catch) and then rethrown.
Note that it's generally bad practice to do catch (Exception) - this is a good example of why. I definitely suggest that rather than doing the above, you simply refactor so that you are no longer catching Exception, which would be a far neater solution.
check this:
try
{
...
}
catch()
{
throw new Execption("I'M A NEW EXCEPTION")
}
finally
{
...
}
Can't you simply add a catch clause with your custom exception?
try
{
//Lots of code
}
catch (OracleException)
{
}
catch (MyCustomException)
{
}
catch (Exception)
{
}
Try this
catch(OracleException ex)
{
throw new MyCustomException(
"MyCustomEX error: Unable to ......", ex);
}