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
}
Related
catch (HttpAntiForgeryException e)
{
throw new HttpAntiForgeryException("Forgery Exception");
}
When I build the project, there is a warning said: The variable 'e' is declared but never used.
Is that because the e is not necessary?
Yes. You can just simply write
catch (HttpAntiForgeryException)
{
throw new HttpAntiForgeryException("Forgery Exception");
}
But, you are rethrowing same type of exception. You can also simply delete this catch block.
It is no necessary if you don't want to do anything with the exception, in your case you are throwing custom message so its fine to use like this :
catch
{
throw new HttpAntiForgeryException("Forgery Exception");
}
or like this :
// For specific exception
catch (HttpAntiForgeryException)
{
throw new HttpAntiForgeryException("Forgery Exception");
}
But you will not get any information regarding this exception, like error message, stack-Trace, inner exception etc.. I prefer you to handle the exception in Catch, Or properly log them for developer's reference
It's because You have not used the Variable e within any where of the catch block. You can easily catch that exception so you will get better understanding of the root cause of your exception than throwing a new exception.
catch (HttpAntiForgeryException e)
{
Console.WriteLine(e.Message); // Console.Writeline or whichever way you want
}
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
}
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.
There has already been a question posted here which is very similar. Mine is extending that question a bit more. Say you want to catch multiple types of exception but want to handle it the same way, is there a way to do something like switch case ?
switch (case)
{
case 1:
case 2:
DoSomething();
break;
case 3:
DoSomethingElse()
break;
}
Is it possible to handle few exceptions the same way . Something like
try
{
}
catch (CustomException ce)
catch (AnotherCustomException ce)
{
//basically do the same thing for these 2 kinds of exception
LogException();
}
catch (SomeOtherException ex)
{
//Do Something else
}
Currently there is no language construct to accomplish what you want. Unless the exception all derive from a base exception you need to consider refactoring the common logic to a method and call it from the different exception handlers.
Alternatively you could do as explained in this question:
Catch multiple Exceptions at once?
Personally I tend to prefer the method-based approach.
You should really have a BaseCustomException and catch that.
This is copied from another posting, but I am pulling the code to this thread:
Catch System.Exception and switch on the types
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
throw;
}
I prefer this to repeating a method call in several catch blocks.
In vb.net, one can use exception filters to say, e.g.
Catch Ex As Exception When TypeOf Ex is ThisException Or TypeOf Ex is ThatException
Unfortunately, for whatever reasons, the implementors of C# have as yet refused to allow exception filtering code to be written within C#.
You shouldn't be catching this many custom exceptions,however if you want you can create a common BaseException and catch that.
I've never actually done this or anything like it, and I don't have access to a compiler for testing purposes but surely something like this would work. Not sure how to actually do the type comparison or if C# would let you replace the if statements with a case statement.
try
{
}
catch (System.Object obj)
{
Type type;
type = obj.GetType() ;
if (type == CustomException || type == AnotherCustomException)
{
//basically do the same thing for these 2 kinds of exception
LogException();
}
else if (type == SomeOtherException ex)
{
//Do Something else
}
else
{
// Wasn't an exception to handle here
throw obj;
}
}
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
}
}
}