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.
Related
The title is a bit misleading but the issue seems very straight-forward to me. I have try-catch-finally block. I want to execute the code in the finally block only if an exception was thrown from the try block. The structure of the code right now is:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
}
finally
{
//execute the code only if exception was thrown.
}
Right now the only solution I can think of is setting a flag like:
try
{
bool IsExceptionThrown = false;
//Do some stuff
}
catch (Exception ex)
{
IsExceptionThrown = true;
//Handle the exception
}
finally
{
if (IsExceptionThrown == true)
{
//execute the code only if exception was thrown.
}
}
Not that I see something bad in this but wonder if there is another(better) approach to check if there's a thrown exception?
What about something like:
try
{
// Do some stuff
}
catch (Exception ex)
{
// Handle the exception
// Execute the code only if exception was thrown.
}
finally
{
// This code will always be executed
}
That's what Catch block are made for!
Don't use finally for this. It is intended for code that should always execute.
What exactly is the difference, in terms of when to execute, between
//Handle the exception
and
//execute the code only if exception was thrown.
I can't see any.
You don't need finally after all:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
//execute the code only if exception was thrown.
}
The Finally part of a Try / Catch statement is always fired regardless of whether any exceptions have been found. I would recommend you don't use it in this scenario.
try
{
// Perform Task
}
catch (Exception x)
{
//Handle the exception error.
}
Finally
{
// Will Always Execute.
}
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.
I am trying to propagate to my UI the GatewayConnectionFailedException as you can see. I want this code to catch everything except that exception which I want the presentation layer to catch to notify the user that the database was the problem so he can go and fix it. My problem is that when I throw it the first time then I get GatewayConnectionFailedException not handled by user code on the GatewayException catch clause.
Its also important to note the the GatewayConnectionFailedException extends GatewayException which extends Exception. Is there something I am missing or will I have to move all the catch to the presentation layer ?
try
{
something();
}
catch (GatewayConnectionFailedException gcfe)
{
throw;
}
catch (GatewayException ge)
{
if (ge.GetType() == typeof(GatewayConnectionFailedException))
throw;
string errMsg = "Records could not be retrieved due to a data gateway error. " + GetTypeInfo();
_logger.Error(errMsg + "\r\n{0}", ge);
}
catch (Exception e)
{
if (e.GetType() == typeof(GatewayConnectionFailedException))
throw;
string errMsg = "Records could not be retrieved due to an unexpected error. " + GetTypeInfo();
_logger.Error(errMsg + "\r\n{0}", e);
}
Stupid question... is your UI code try-catching in it's call to this layer? Something has to handle that second throw...
In a nutshell, it sounds like you're trying to do this:
using System;
namespace ConsoleApplication1
{
class ExceptionA : Exception
{
public override string Message
{
get
{
return "Exception A";
}
}
}
class ExceptionB : ExceptionA
{
public override string Message
{
get
{
return "Exception B";
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
DoThing();
}
catch (Exception ex)
{
Console.WriteLine("Caught in 'UI' code: " + ex.Message);
}
}
static void DoThing()
{
try
{
throw new ExceptionB();
}
catch (ExceptionB ex)
{
Console.WriteLine("Caught B");
throw;
}
catch (ExceptionA ex)
{
Console.WriteLine("Caught A");
}
catch (Exception ex)
{
Console.WriteLine("Caught Generic");
}
}
}
}
Which yields this output:
Caught B
Caught in 'UI' code:
Exception B
Press any key to continue...
It just seems like you don't have anything catching the 2nd thrown exception, which is why it's "unhandled." If we comment out the try-catch in main, we end up with an unhandled exception:
static void Main(string[] args)
{
//try
//{
DoThing();
//}
//catch (Exception ex)
//{
//Console.WriteLine("Caught in 'UI' code: " + ex.Message);
//}
}
Yielding the following output:
Caught B
Unhandled Exception: ConsoleApplication1.ExceptionB: Exception B
at ConsoleApplication1.Program.DoThing() in C:\Users\Giovanni\AppData\Local\T
emporary Projects\ConsoleApplication1\Program.cs:line 50
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Giovanni\AppDa
ta\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 33
Press any key to continue . . .
One item to not although this might not fix the exception, if you are catching and rethrowing the exception use this code instead:
catch (GatewayConnectionFailedException)
{
throw;
}
this way the stacktrace reflects the programs journey more accurately. It may not solve the issue though.
Hard to tell what is missing without full picture, but one important thing that you should throw exceptions in different way. The syntax should be
throw;
you will have full stacktrace. More info.
Catching of GatewayConnectionFailedException should solve your problem and in catch block just do throw, don't throw the exception object. Answer by Andy is correct.
Secondly I'm assuming GatewayConnectionFailedException inherits from GatewayException.
Select catch sequence in ascending of order of inheritance, child class should come first and then base class.
catch(Child){}
catch(Base){}
catch(Exception) {} //Base class for all exceptions
to start your try catch is redundant. the first catch will handle GatewayConnectionFailedException the remaining catches will never be of type GatewayConnectionFailedException because they were handled by the first catch. so the code can be simplified to
try
{
something();
}
catch (GatewayConnectionFailedException)
{
throw;
}
catch (GatewayException e)
{
_logger.Error(e.Message, e);
}
Now how the UI will handle this depends on how you handle the exception. if you just throw the exception, then you need a try catch in the presentation layer as well. However if the return type of this layer returned an object like
class Result<T>
{
T Value {get;set;}
Exception Error {get;set;}
}
Then you could simply process the type without need try/catch in the presentation layer.
Also worth noting is what you are catching and why you are trying to catch it. typically you don't want to catch Exception except at the application layer where you log the error and fail. Exceptions should be exceptional, and therefore only catch exceptions you expect can happen and why they may happen. otherwise let them bubble up.
Instead of using throw exceptionName try only throw.
Edit 1:
Try catching all exceptions in the same block, then throw back the exception only if it's the GatewayConnectionFailedException
try
{
something();
}
catch (Exception e)
{
if (e.GetType() == typeof(GatewayConnectionFailedException))
throw;
string errMsg = "Records could not be retrieved due to an unexpected error. " + GetTypeInfo();
_logger.Error(errMsg + "\r\n{0}", e);
}
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);
}