Can I execute multiple Catch blocks? - c#

This is a bit abstract, but is there any possible way to throw an exception and have it enter multiple catch blocks? For example, if it matches a specific exception followed by a non-specific exception.
catch(Arithmetic exception)
{
//do stuff
}
catch(Exception exception)
{
//do stuff
}

It is perfectly acceptable to have multiple catch blocks of differring types. However, the behavior is that the first candidate block handles the exception.
It will not enter BOTH catch blocks. The first catch block that matches the exception type will handle that specific exception, and no others, even if it's rethrown in the handler. Any subsequent ones will be skipped once an exception enters a catch block.
In order to have an exception caught in BOTH blocks, you would need to either nest blocks like so:
try
{
try
{
// Do something that throws ArithmeticException
}
catch(ArithmeticException arithException)
{
// This handles the thrown exception....
throw; // Rethrow so the outer handler sees it too
}
}
catch (Exception e)
{
// This gets hit as well, now, since the "inner" block rethrew the exception
}
Alternatively, you could filter in a generic exception handler based on the specific type of exception.

No. It isn't possible to execute the code in both catch blocks for a single exception.
I would probably refactor the code in the generic exception block into something that can be called from either.
try
{
// blah blah blah
{
catch(Arithmetic ae)
{
HandleArithmeticException( ae );
HandleGenericException( ae );
}
catch(Exception e)
{
HandleGenericException( e );
}

Like others said the exception will be caught by the most specific catch block.
This brings up a frustration of mine though with exception handling. I wish you could do something like
catch (ArgumentNullExcpetion, ArugmentOutOfRangeException ex)
{
}
Instead of having to do
catch (ArgumentNullExcpetion e)
{
}
catch (ArugmentOutOfRangeException outOfRange)
{
}
I understand the reasoning against this that you probably do different things for different exceptions but sometimes I want combine them.

You can't have more than one exception block handle the same exception. But what you can do is catch the general exception, then attempt to cast to the more specific, like this:
catch (Exception exception)
{
var aex = exception as ArithmeticException
if (aex != null)
{
// do stuff specific to this exception type
}
// then do general stuff
}

If you were using VB.NET you could abstract your error handler in the Arithmetic exception into a function or method call that always returns false.
Then you could write something like:
Catch ex as Arithmetic When HandleArithmetic()
Catch ex as Exception
End Try
Not that I would advocate such usage, though I have seen it recommended for logging purposes before. I don't believe there is a C# equivalent.

This is known as exception filtering and isn't supported in C# (I'm told it is possible in VB.NET).
One work around would be to catch the general exception and then check the exception type in the catch block and do any specific processing on that before carrying on with the rest of the block.

Related

When does the catch arguments get checked in a try/catch block c#

I'm having an issue with a try/catch block, but I can't seem to find out exactly how try/catch works when it's running that I think might have my answer. I have the following try/catch block:
try
{
...
}
catch (MyException e)
{
Log.Error("oh no!");
throw;
}
Now when I run this code I'm getting a System.TypeLoadException: Could not load type SDK.MyException from assembly "SDKSampleLibrary, Version... etc error.
I'm wondering 2 things. First, when does the computer check to see if MyException is there. Is it when it gets to the try or when it gets to the catch? Second, the SDKSampleLibrary.dll is there. How do I tell why it's not seeing it?
If the class MyException gets thrown within the try area, it will get handled inside the catch, See my example below where i throw a new exception which would get handled by the catch statement. However any other kinds of exceptions would not be handled/
try
{
throw(new MyException()); // handled by the catch
throw(new ParseException()); //not handled.
int test = "test" //not handled
}
catch (MyException e)
{
Log.Error("oh no!");
throw;
}
can also catch general exceptions to catch ALL exceptions like:
try
{
throw(new MyException()); // handled by the catch
throw(new ParseException()); //handled.
int test = "test" //handled
}
catch (Exception e)
{
Log.Error("oh no!");
throw;
}
The compiler sees the class since it is blue and does not give compile errors. The problems is happening when you are running the code. I think the problem is in de code that throws the exception which cannot create it. You could try to use the normal Exception type in the catch block and then set a break point.
The problem is not with the try/catch block but rather the problem is the type of exception that you are trying to catch as specified by the exception that your code is throwing. This exception occurs when the runtime tries to load the MyException object. You should make sure that the MyException inherits either from the Exception base class or from any of its children.

Is this try-catch block valid?

Newby question...
Is it valid to do:
try
{
// code which may fail
}
catch
{
Console.Writeline("Some message");
}
Or do I always have to use:
try
{
// code which may fail
}
catch (Exception e)
{
Console.Writeline("Some message");
}
Both blocks are valid.
The first will not have an exception variable.
If you are not going to do anything with the exception variable but still want to catch specific exceptions, you can also do:
try
{
// your code here
}
catch(SpecificException)
{
// do something - perhaps you know the exception is benign
}
However, for readability I would go with the second option and use the exception variable. One of the worst things to do with exceptions is swallow them silently - at the minimum, log the exception.
Yep, absolutely, such a catch block called general catch clause, see more interesting details in the C# Language Specification 4.0, 8.10 The try statement:
A catch clause that specifies neither an exception type nor an
exception variable name is called a general catch clause. A try
statement can only have one general catch clause, and if one is
present it must be the last catch clause
Yes, your first block of code valid. It will catch all exceptions.
It is. It will catch all the exception. So the two code examples do the same.
First one is valid, and it acts just like the second one.
http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx
The catch clause can be used without arguments, in which case it
catches any type of exception, and referred to as the general catch
clause. It can also take an object argument derived from
System.Exception, in which case it handles a specific exception.
Yes it is valid.
you can always refer to this article:
Best Practices for Handling Exceptions on MSDN
Of course it is valid, you specify catch(Exception e) when you want to output the error message ex.Message, or to catch a custom or a concrete Exception. Use catch in your situation.
As #David answered this is valid.
You could use second syntax if you want to get more infos or catch a specific exception.
E.g.
catch (Exception e)
{
Debug.Print(e.Message);
}
catch (Exception e)
{
Console.Writeline("Some message");
}
In this block you can use SqlException, etc..
catch (SqlException e)
{
Console.Writeline("Some message");
}
For this use the "(SqlException e)"
If you will use a generic menssage, use this:
catch
{
Console.Writeline("Some message");
}
or
catch (Exception)
{
Console.Writeline("Some message");
}
Don't forget that you can chain catch your exceptions. This will allow you to handle different scenarios based upon the exception(s) the code may throw.
try
{
//Your code.
}
catch(SpecificException specificException)
{
//Handle the SpecificException
}
catch(AnotherSpecificException anotherSpecificException)
{
//Handle AnotherSpecificException
}
catch(Exception exception)
{
//Handle any Exception
}

using catch for a customized situation

Is it possible to call catch for a special condition when you are inside of try without using system error? For instance if a value int value 1 and then I want to use "catch".
One of the biggest sins in programming:) Don't use exceptions for managing programming flow! Now to your question - the catch block can be called in case an exception is thrown.
Your wording is a bit confusing but I think this is what you want.
int value = GetValue();
try
{
if (value == 1)
throw new InvalidOperationException();
HappyPath(value);
}
catch (InvalidOperationException)
{
SadPath(value);
}
Incidentally using exceptions for control flow is not the best practice.
No. You should catch exceptions (you can filter them by type), and then inside catch block you can filter on any condition.
It is not possible in C# to throw an exception that doesn’t derive from Exception, even though the CLR allows it.
It is possible to catch such an exception, but it is not possible to access the object that was thrown:
try
{
MethodThatThrows();
}
catch // This catches everything, even objects not deriving from Exception
{
// Process exception
}
As soon as you specify a variable (e.g. catch (Exception e)), C# requires that the type is Exception or derived from it.
I think you might be saying that you want to catch an exception only in specific circumstances, and pass it through in all other circumstances? In that case, you can just use an if to check for the condition and then throw to re-throw the exception:
try
{
// ...
}
catch (Exception e)
{
// If it’s any value other than 1, we’re not interested in the exception
if (value != 1)
throw; // note: throw; *not* throw e;
// Process the exception here
}

Exception Handling

Is there a way in C# to catch any kind of exception?
Like in C++ to catch any kind of exception
the format is like
try{
//Statements
}
catch(...){
// Some more statements
}
But this format in c# fails.
Help?
You can catch anything like :
catch {}
From .NET 2 and further, this is equivalent to:
catch(Exception ex) {}
Because every exception (even a Windows SEH exception) is guaranteed to be derived from System.Exception.
Check this link out. It's all about exceptions.
What you are trying to do is use a parameter-less catch like this:
try {
// your code
} catch {
// any exception
}
try {
// Statements
} catch (Exception ex) {
// Do stuff with ex
}
That should work.
catch(Exception ex)
or catch() <-- i believe the second one works
The .NET framework provides a mechanism to detect/handle run time errors. C# uses three keywords in exception handling: try, catch, finally. The try block contains the statement that can cause an exception. The catch block handles the exception, and the finally block is used for cleaning up.
try
{
//statements that can cause an exception
}
catch(Type x)
{
//statements for handling an exception
}
finally
{
//cleanup code
}

Exception.Data and Exception Handling Questions

I have a couple questions about exceptions.
1) when you hit a catch block, swallowing means what exactly? I thought it was always rethrow or the existing exceptions is passed up to the next catch block.
2) If you add Exception.Data values to an excepction, I notice I have to do another throw; to grab that data futher up in another catch block later. Why?
Swallowing an exception means catching it and not doing anything useful with it. A common thing you might see is this:
try
{
DoSomeOperationThatMightThrow();
}
catch (Exception ex) // don't do this!
{
// exception swallowed
}
You usually don't want to catch a base Exception at all, it's better to catch and handle specific Exception types, and ideally you should only catch exception types that you can do something useful with at the level of code you're in. This can be tricky in complex applications, because you might be handling different errors at different levels in the code. The highest level of code might just catch serious/fatal exceptions, and lower levels might catch exceptions that can be dealt with with some error handling logic.
If you do catch an exception and need to rethrow it, do this:
try
{
DoSomething();
}
catch (SomeException ex)
{
HandleError(...);
// rethrow the exception you caught
throw;
// Or wrap the exception in another type that can be handled higher up.
// Set ex as the InnerException on the new one you're throwing, so it
// can be viewed at a higher level.
//throw new HigherLevelException(ex);
// Don't do this, it will reset the StackTrace on ex,
// which makes it harder to track down the root issue
//throw ex;
}
Swallowing an exception normally means having a handling block for the exception, but not doing anything in the block. For example:
try { 3/0; } catch DivideByZeroException { //ignore } //Note: I know this really wont' compile because the compiler is smart enough to not let you divide by a const of 0.
You have to rethrow because the first handler for an exception is the only one that will execute.
If you want the exception to bubble up you either don't handle it or you rethrow it. By the way, it's important to note that in .NET by just saying "throw" you'll preserve the stack trace. If you "throw Exception" you'll lose your stack trace.
Ok, you can handle the exception up to call stack you can do some thing like this:
public class A
{
public void methodA()
{
try
{
}
catch(Exception e)
{
throw new Exception("Some description", e);
}
}
}
public class B
{
public void methodB()
{
try
{
A a = new A();
a.methodA();
}
catch(Exception e)
{
//...here you get exceptions
}
}
}

Categories

Resources