Why Throw An Exception Rather Than Letting The Code Throw It? - c#

I want the code calling a function to handle any exception raised in the function. If I write:
try
{
// Code than may raise an exception
}
catch
{
throw;
}
The exception will be passed back with the callstack. Could I write the following instead and get the same result? Is there any reason to use the try catch in this case?
// Code that may raise an exception

In the scenario you've presented, the only reason to catch, and then rethrow, the exception, is if you're doing something else in the catch block, like logging or cleanup. Otherwise, it's entirely a no-op.
Good on you that you're using throw, rather than throw e, by the way, if you do need this construct. The former preserves the callstack; the latter does not.

There is no reason to use try/catch in that case.
If you were logging any information or encapsulating the exception in a higher-level one, then the try/catch would be indicated.

Related

Catch exception not of a type

Is there a difference when catching exceptions not of a type between :
try
{
...
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception exception)
{
...
}
and :
try
{
...
}
catch (Exception exception) when (!(exception is TaskCanceledException))
{
...
}
Yes, there is.
In the second block of code you are filtering on general exception type. It is not meant to be filtered, what happens if "TaskCanceledException" is thrown? you are not handling it and it will escalate to enclosing code. You are not really meant to filter anything on "Exception" type since it is the parent for all other type of exception and it is the last point of handling exception. A better option would be to create a custom exception and put them in separate block of catch and filter on them if needed.
The first option is more correct compared to the second one. Though you should not be throwing any exception and stay away from them, unless it is a complete deal breaker. On top of that what is the point of putting a catch block with Exception type bellow TaskCanceledException catch block which throws exception? You are basically telling that "I Would like to handle all exception" when using catch with Exception type, but at the same time you through one exception in exceptional case. Either throw the original exception or handle them.
Hope this makes sense.
Refer to this link Stackoverflow
Catch blocks already allow you to filter on the type of the exception:
catch (SomeSpecificExceptionType e) {...}
The when clause allows you to extend this filter to generic expressions.
Thus, you use the when clause for cases where the type of the exception is not distinct enough to determine whether the exception should be handled here or not.
The Dixin's Blog explained the difference with code example and VS screenshots.
Exception filter does not unwind the stack, and catch block does unwind. When executing catch block, this catch block’s method becomes the top frame of the stack. As a result, all the methods called by current method are removed from the stack. In contrast, exception filter can be helpful for runtime debugging. For example, if above Catch method is executed:

How to avoid catching generic exceptions

In my processing I would like to log any error along with the user and code details and proceed on with my work.
I am currently using a try catch block which includes a generic catch, but is catching a generic exception is a bad thing? Such as the exception could be a stackoverflowexception or outofmemoryexception and need to be handled differently.. .
But I am not sure how to avoid catching these fatal exceptions. I am looking for suggestions.
Why I want to catch all exceptions
Because I don't want a failure in one form's processing to affect the others in the loop.
Why I am catching specific exceptions:
I understand I can look for stackoverflowexception, outofmemoryexception etc... but my point is, there could be many of them...looking for each and every would make my code lengthy. I am not sure if that is the best process.
But I am not sure how to avoid catching these fatal exceptions
Well, 2 things.
First, you can always rethrow them, for example, after logging.
Second, you can catch every exception you want and if you do not catch System.Exception then all you do not catch will bubble up - that is C# 101 for beginners, so if you have a problem with that, back to reading the documentation about exceptions in general.
Exceptions cascade down. If you want to handle certain exceptions differently, implement a different catch block.
try
{
ThisMethodMayThrowException();
}
catch(StackOverflowException ex)
{
//handle a StackOverFlowException
}
catch(OutOfMemoryException ex)
{
//handle a OutOfMemoryException
}
catch(Exception ex)
{
//handle all other types.
}
In general though, you should only plan to handle expected exceptions. For example, if you're writing to a file that you expect to exist, you might anticipate a FileNotFoundException. If you tried to handle every possible exception, your code would become quite long and unwieldy, to little benefit.
Microsoft provides excellent info on exception handling.
Reverse your thinking... because the advice catching generic exception is being misinterpreted.
Handle all exceptions which are known explicitly (do the log and continue processing), but always have a generic catch all exception handler to stop all processing and handle that unknown.
In your example an overflow exception could comprise data or let malicious actors take over the system in unexpected ways; hence continuing on, should not be done.
If you know all the exceptions you want to catch, you write a catch block for each specifically:
try
{
}
catch (IOException)
{
}
catch (InvalidCastException)
{
}
...
Then all the ones you don't want to catch (and thus allow to potentially take down your program) will keep bubbling up.
I am currently using a try catch block which includes a generic catch,
but I have heard from many people that catching generic exception is a
bad thing(as the exception could be a stackoverflowexception or
outofmemoryexception).
You should know which Exception types your method calls might throw.
It could be discovered either at the Method documentation, example:
/// <exception cref="DivideByZeroException">Why it's thrown.</exception>
public void MethodThatMightThrowDivideByZeroException(){...}
or by looking at the Method code, example:
throw new DivideByZeroException();
That way, you would be able to catch it easily:
try
{
ThisMethodMayThrowException();
}
catch(DivideByZeroException ex)
{
//handle a DivideByZeroException
}

one main try catch in method calling methods that don't implement a try-catch

I have a method doSomething() that has one try catch block, within which I call another method.
public void doSomething()
{
try
{
doSomethingElse();
}
catch
{
// catch implementation goes here
}
}
In that other method doSomethingElse() I don't have any try catch block. I am depending on the main method's try-catch to handle the exception. If there are any exceptions in doSomethingElse() they will be bubbled up to the method doSomething's try-catch block.
Is there anything wrong with this approach?
Thanks for your time.
This is perfectly legitimate.
Let exceptions bubble up to where you can/know what to do with them.
It is good practice not to litter your code with try/catch blocks that don't add anything.
However, having empty catch blocks is bad practice (though I am assuming the code you have posted is a simplified version omitting the catch block code).
Nothing wrong with that.
As others have said, don't swallow exceptions. It may also be a good idea not to throw a new exception; rather, just catch (Exception) and throw it. Of course, it should also be noted to try and be specific with exceptions, and not just use the default Exception.
It's smelly. Catching an exception requires that you restore the program state, as though doSomethingElse() was never called. It very much depends on what the method does but it is generally pretty unusual to write a method without any side effects whatsoever. If it has any then those side effects need to be canceled. Only doSomethingElse() can do so, the doSomething() method is powerless to guess how many of those side effects were actually executed. And can thus not reliably restore state.
This is especially the case when you catch all exceptions. You'll grab the nasty ones as well. Like AccessViolation or FatalExecutionEngineError, exceptions that leave the CLR itself in a unknown state, you can never restore that. What happens next is quite unpredictable. You'll get a flurry of additional exceptions only if you're lucky. Diagnosing them is impossible, you threw away valuable info.
This is ok, but you forget about ; after doSomethingElse()

Do I have to break after throwing exception?

I'm writing a custom class in C# and I'm throwing a couple exceptions if people give the wrong inputs in some of the methods. If the exception is thrown, will any of the code in the method after the throw still be executed? Do I have to put a break after the throw, or does a throw always quit the method?
When you throw an exception, the next code to get executed is any catch block that covers that throw within the method (if any) then, the finally block (if any). You can have a try, a try-catch, a try-catch-finally or a try-finally. Then, if the exception is not handled, re-thrown by a catch block or not caught at all, control is returned to the caller. For example, you will get "Yes1, Yes2, Yes3" from this code ...
try
{
Console.WriteLine("Yes1");
throw (new Exception());
Console.WriteLine("No1");
}
catch
{
Console.WriteLine("Yes2");
throw;
Console.WriteLine("No2");
}
finally
{
Console.WriteLine("Yes3");
}
Console.WriteLine("No3");
Throw will move up the stack, thus exiting the method.
I recommend stepping through your program with a debugger then you'll see for yourself what is going on. Very useful for learning!
I came here looking for an answer to the original post and almost missed a very valuable answer posted by Eric Lippert. Here's his answer posted in the comments:
Split this up into three questions.
(1) Will any of the code in the method after the throw be executed?
YES. If the exception was inside a try then code inside matching catch blocks or finally block will be executed. If there is no try block then NO. Control branches to the nearest enclosing finally, catch or (in vb) exception filter block up the stack.
(2) Do I have to put a break after the throw?
NO, never do that. The end point of the throw statement is not reachable; a throw is treated as a goto by the compiler. A statement immediately following a throw is not reachable and will never execute.
(3) Does a throw always quit the method?
NO. If the throw is in a try and the try has a matching catch block then the catch block can "eat" the exception. Only if there is no catch block does the exception do a non-local goto up the call stack.
If you have more questions about this, I recommend reading the C# specification; all this behavior is clearly documented.
Finally, it sounds like you are throwing "boneheaded" exceptions, as in "hey boneheaded caller, I told you to never give me that data". That's great because it prevents bugs in callers. But if you do that, you should make sure that the caller has some way of knowing what you expect! If the caller cannot figure out whether you're going to throw or not based on your documentation, then you haven't made a boneheaded exception, you've made a vexing exception. See http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx for details.
If you've wrapped your code in a Try...Catch...Finally block, then the code under Finally will always execute. For example:
Try
' do some stuff here
' Examine user input
If user input isn't valid
Throw new exception
Catch
Throw ' Just re-throws the same exception
Finally
' This code will execute, no matter what - exception or not
End Try
As an aside to your actual question: you might want to rethink using exceptions to provide validation info back to the user.
Raising exceptions is expensive resource-wise and slow. If you have a number of validation rules that you need to apply then write specific code for these - you should probably only rely on exception handling for things you don't anticipate.

What is "throw"

Can anyone please explain me use of throw in exception handling?
What happens when i throw an exception?
It means to "cause" an exception. When you "throw" an exception you are saying "something has gone wrong, here's some details".
You can then "catch" a "thrown" exception to allow your program to degrade gracefully instead of erroring and dying.
"Throwing" an exception is what triggers the entire process of exception handling.
In the course of normal execution, lines in a program are executed sequentially with loops and branches. When an error of some sort happens, an exception is created and then thrown.
A thrown exception will modify the usual order of operations in a program in such a way that no "normal" instructions will be executed until the exception is handled within a "catch" block somewhere. Once an exception is caught in a catch block, and the code within that catch block is executed ("Handling" the exception), normal program execution will resume immediately following the catch block.
// Do some stuff, an exception thrown here won't be caught.
try
{
// Do stuff
throw new InvalidOperationException("Some state was invalid.");
// Nothing here will be executed because the exception has been thrown
}
catch(InvalidOperationException ex) // Catch and handle the exception
{
// This code is responsible for dealing with the error condition
// that prompted the exception to be thrown. We choose to name
// the exception "ex" in this block.
}
// This code will continue to execute as usual because the exception
// has been handled.
When you throw an exception you're basically saying that some condition has happened beyond the reasonable means of the caller being expected to handle it. They're especially useful in constructors which have no way of signaling any form of construction failure (as they don't have return values).
When you throw an exception the runtime moves up the execution chain until it finds a catch block that is assignable to the type of exception you've thrown. On the way it runs the code in any finally blocks you may have, which allows you to (typically) release any resources you may have acquired.
The throw creates the exception to be handled. The object you passed then becomes the data that describes the exception.
Until something is thrown there is no exception to be handled.
Throwing an exception causes the exception to rise up the stack. There are two primary scenarios for a throw.
Have an exceptional condition unique to your code
if(inputVal < 0)
{
throw new LessThanZeroCustomException("You cannot enter a value less than zero");
}
The above code assumes you have coded an exception object called LessThanZeroCustomException. I would not actually name it this, but the Custom in the name is designed to illustrate you coded this. It would most likely inherit from
Have an exceptional condition that has been caught and needs to be rethrown. The normal reason for this is logging. In most cases, I dislike this pattern, as you end up spending time catching, logging and throwing over and over again. This is because most people doing this pattern try ... catch at every level. Yuck!
In short, throw means "I found an exceptional condition I cannot handle, so I am letting the person using this code know by throwing an exception".

Categories