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".
Related
I thought I had understood how exception handling in C# works. Re-reading the documentation for fun and self-confidence, I have run into problems:
This document claims that the following two code snippets are equivalent, even more, that the first one is translated to the latter one at compile time.
using (Font font1 = new Font("Arial", 10.0f)) {
byte charset = font1.GdiCharSet;
}
and
{
Font font1 = new Font("Arial", 10.0f);
try {
byte charset = font1.GdiCharSet;
}
finally {
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Furthermore, it claims:
The using statement ensures that Dispose is called even if an
exception occurs while you are calling methods on the object.
In contrast, that document states:
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered.
I do not get this together. In the code example from the first document, the exception clearly is unhandled (since there is no catch block). Now, if the statement from the second document is true, the finally block is not guaranteed to execute. This ultimately contradicts what the first document says ("The using statement ensures ...") (emphasis mine).
So what is the truth?
EDIT 1
I still don't get it. StevieB's answer has made me read more parts from the C# language specification. In section 16.3, we have:
[...] This search continues until a catch clause is found that can
handle the current exception [...] Once a matching catch clause is
found, the system prepares to transfer control to the first statement
of the catch clause. Before execution of the catch clause begins, the
system first executes, in order, any finally clauses that were
associated with try statements more nested that than the one that
caught the exception.
So have I made a simple test program which contains code which produces a division by zero and is within a try block. That exception is never caught in any of my code, but the respective try statement has a finally block:
int b = 0;
try {
int a = 10 / b;
}
finally {
MessageBox.Show("Hello");
}
Initially, according to the documentation snippet above, I had expected that the finally block never would be executed and that the program just would die when being executed without a debugger attached. But this is not the case; instead, the "exception dialog box" we all know too well is shown, and after that, the "Hello" dialog box appears.
After thinking a while about that and after having read docs, articles and questions like this and that, it became clear that this "exception dialog box" is produced by a standard exception handler which is built into Application.Run() and the other usual methods which could "start" your program, so I am not wondering any more why the finally block is run.
But I am still totally baffled because the "Hello" dialog appears after the "exception dialog box". The documentation snippet above is pretty clear (well, probably I am just too silly again):
The CLR won't find a catch clause which is associated with the try statement where the division by zero happens. So it should pass the exception up one level to the caller, won't find a matching catch clause there as well (there is not even a try statement there) and so on (as noted above, I do not handle (i.e. catch) any exception in this test program).
Finally, the exception should meet the CLR's default catch-all exception handler (i.e. that one which is by default active in Application.Run() and its friends), but (according to the documentation above) the CLR should now execute all finally blocks which are more deeply nested than that default handler ("my" finally block belongs to these, doesn't it?) before executing the CLR catch-all default handler's catch block.
That means that the "Hello" dialog should appear before the "exception dialog box", doesn't it?. Well, obviously, it's the other way around. Could somebody elaborate on that?
This document claims that the following two code snippets are equivalent
They are.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
Pretty much.
This ultimately contradicts what the first document says
Well, the first one was being a bit too vague, rather than flat-out incorrect.
There are cases where a finally will not run, including that implied by a using. A StackOverflowException would be one example (a real one from overflowing the stack, if you just do throw new StackOverflowException() the finally will run).
All the examples are things you can't catch, and your application is going down, so if the clean up from using is only important while the application is running, then finally is fine.
If the clean-up is vital even when the program crashes, then finally can never be enough, as it can't deal with e.g. a power plug being pulled out, which in the sort of cases where clean up is vital even in a crash, is a case that needs to be considered.
In any case where the exception is caught further up and the program continues, the finally will run.
With catchable exceptions that aren't caught, then finally blocks will generally run, but there are still some exceptions. One would be if the try-finally was inside a finaliser and the try took a long time; after a while on the finaliser queue the application will just fail-fast.
If your definition of "unhandled exception" (that it must be handled by a catch clause within the same try block) was correct, there would be no reason to ever allow the construct
try {
...
}
finally {
...
}
Since by your definition, the finally block would never run. Since the above construct is valid, we must conclude that your definition of "unhandled exception" is incorrect.
What it means is "if the exception is not handled by any exception handler, anywhere in the call stack".
You have to give the documentation a little leeway. In most circumstances there's an implied "within reason". For example, if I turn my computer off none of those finally blocks or using/Disposes will be called.
Apart from the computer shutting off, there are a handful of circumstances that OS can terminate your application--effectively shutting it off. In these circumstances Dispose and finally won't be invoked. Those are usually pretty serious error conditions like out of stack or out of memory. There are some complex scenarios where that can happen with less-than-exceptional-exceptions. For example, if you have native code that creates a managed object on a background thread and that managed object and something on that thread throws an native exception, it's likely that the managed exception handlers won't get called (e.g. Dispose) because the OS will just terminate the thread and anything that could have been disposed is not accessible any more.
But, yes, those statements are effectively equivalent and within reason the finally block will be executed and Dispose will be called.
The C# language specification states that the finally blocks will be executed (be that in a using statement or elsewhere) for System.Exception or any of its derived exceptions. Of course, if you get an exception that can't be handled with the usual try..catch logic e.g. AccessViolationException all bets are off which is where the ambiguity comes in.
The spec is installed with Visual Studio 2013 and later - with 2017 it's in C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC#\Specifications\1033
In section
8.9.5 The throw statement
we see the following:
When an exception is thrown, control is transferred
to the first catch clause in an enclosing try statement that can
handle the exception. The process that takes place from the point of
the exception being thrown to the point of transferring control to a
suitable exception handler is known as exception propagation.
Propagation of an exception consists of repeatedly evaluating the
following steps until a catch clause that matches the exception is
found. In this description, the throw point is initially the location
at which the exception is thrown.
In the current function member,
each try statement that encloses the throw point is examined. For each
statement S, starting with the innermost try statement and ending with
the outermost try statement, the following steps are evaluated:
If
the try block of S encloses the throw point and if S has one or more
catch clauses, the catch clauses are examined in order of appearance
to locate a suitable handler for the exception. The first catch clause
that specifies the exception type or a base type of the exception type
is considered a match. A general catch clause (§8.10) is considered a
match for any exception type. If a matching catch clause is located,
the exception propagation is completed by transferring control to the
block of that catch clause.
Otherwise, if the try block or a catch
block of S encloses the throw point and if S has a finally block,
control is transferred to the finally block. If the finally block
throws another exception, processing of the current exception is
terminated. Otherwise, when control reaches the end point of the
finally block, processing of the current exception is continued.
If
an exception handler was not located in the current function
invocation, the function invocation is terminated, and one of the
following occurs:
If the current function is non-async, the steps
above are repeated for the caller of the function with a throw point
corresponding to the statement from which the function member was
invoked.
If the current function is async and task-returning, the
exception is recorded in the return task, which is put into a faulted
or cancelled state as described in §10.14.1.
If the current function
is async and void-returning, the synchronization context of the
current thread is notified as described in §10.14.2.
If the
exception processing terminates all function member invocations in the
current thread, indicating that the thread has no handler for the
exception, then the thread is itself terminated. The impact of such
termination is implementation-defined.
I believe (correct me if I am wrong) the answer is lying in the definition:
The using statement ensures that Dispose is called even if an
exception occurs while you are calling methods on the object.
So if any exceptions occur in any methods called by the object of using, finally is ensured to run. On the other hand finally is not guaranteed to run if inside the using block call other methods not related with the object cause an exception
First of all, I would like to bring to your notice that using statement cannot be used for all types. This can be used only for types that implement IDisposable interface which has a functionality to dispose the object automatically. This is present in the second document you mentioned
C# also contains the using statement, which provides similar functionality for IDisposable objects in a convenient syntax.
This means if an unhandled exception happens, cleaning up of your objects is handled by the Dispose() method of the type(this is given for using statement documentation)
Coming to the query, even though your finally block(generated) is not guarenteed to run for unhandled exceptions, the object dispose operation is handled during runtime by .Net CLR
Hope this clears your doubt
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.
Why is it adviced most of the time that we should not trap errors like "Exception" but trap errors that we expect as developers.
Is there a performance hit in trapping generic errors or is it recommended from a best practice point of view?
try
{
// Do something
}
catch(Exception e)
{
//Log error
}
The best practice is to catch specific exception first and then move on to more generic ones.
Exception Handling (C# Programming Guide)
Multiple catch blocks with different exception filters can be chained
together. The catch blocks are evaluated from top to bottom in your
code, but only one catch block is executed for each exception that is
thrown. The first catch block that specifies the exact type or a base
class of the thrown exception is executed. If no catch block specifies
a matching exception filter, a catch block that does not have a filter
is selected, if one is present in the statement. It is important to
position catch blocks with the most specific (that is, the most
derived) exception types first.
For your question:
Why is it adviced most of the time that we should not trap errors like
"Exception" but trap errors that we expect as developers.
An example would be to catch NullReferenceException. Its never a better practice to catch NullReferenceException, instead one should always check for object being null before using its instance members. For example in case of string.
string str = null;
try
{
Console.WriteLine(str.Length)
}
catch(NullReferenceException ne)
{
//exception handling.
}
instead a check should be in place for checking against null.
if(str != null)
Console.WriteLine(str.Length);
EDIT:
I think I got the question wrong, If you are asking which exception should be caught and which shouldn't then IMO, those exceptions which can be dealt with should be caught and rest should be left in the library so they can bubble up to upper layer where appropriate handling would be done. An example would be Violation of Primary key constraint. If the application is taking input(including primary key) from the user and that date is being inserted into the database, then that exception can be caught and a message can be shown to user "Record already exists" and then let the user enter some different value.
But if the exception is related to the foreign key constraint (e.g. Some value from the dropdown list is considered invalid foreign key) then that exception should bubble up and a generic exception handler should log it in appropriate place.
For example in ASP.Net applications, these exception can be logged in Application_Error event and a general error page can be shown to the user.
EDIT 2:
For the OP's comment:
if at a low level if there would be a performance degeradation in
catching a generic error inspite of knowing if the error is
sqlexception
Even if there is going to be any performance difference it should be negligible. But Catch the specific exception, if you know that the exception is going to be SqlException then catch that.
You should only catch exceptions what you can handle. Exception is too generic so most of the time you cannot say you can handle that. It is a little funny but you should only catch exception that you except :)
There are situation when you need to catch Exception but rare and you should avoid it most of the time. Usually it indicates some design problem.
Check Eric Lippert's blog (Vexing exceptions) about best way to handle exceptions.
• Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
• Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
• Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
• Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.
Using exception handling more often than required is infact a lazy way of programming more than anything. Say you have a DataTable and you want to access the first row.
public DataRow AccessFirstRow(DataTable dt)
{
try
{
return dt.Rows[0];
}
catch (Exception e)
{
//There isn't a first row or dt is null
}
}
Instead of
public DataRow AccessFirstRow(DataTable dt)
{
if(dt != null)
if(dt.Rows.Count > 0)
return dt.Rows[0];
//If we can't access dt, then don't
return null;
}
My rule of thumb is:
Exceptions should only be used in EXCEPTION-al circumstances.
If you do decide to handle them though, as mentioned handle specific exceptions you know you might encounter instead of generic exceptions.
It's a best practice thing. The idea is that you should quickly handle the known exceptions explicitly while having more general ones higher up in the program as unexpected exceptions are likely caused by some more major/fundamental error.
Catch those exceptions which you intend to handle. You will usually want to handle particular exception in such context (method) where you have enough information for dealing with error reported (e.g. access to objects used for clean-up).
If code within try block throws different types of exceptions, you might want to handle some exceptions within the same method and re-throw others in order to handle them in the caller method (as in that context you have resources for handling those exceptions).
I am working on application where user invokes a method from UI , on this I am calling a method from business class which calls another methods
UI--> Method1 -->Method2 --> Method3
I want to display the error message to user if any exception occurs in any of the method.
Shall I go with throwing the exception directly to the caller method and at the UI layer I will catch exception and display the message.
Apart from Throwing exceptions and catching it at caller is there any better way to handle it?
I do not want to use the C++ convention where integer is returned as the result.
If you can't recover from the exception in the method where the exception happens, don't try to catch it (unless you want to log it, in which case throw it again after logging). Then catch at the UI-level.
Trying to catch exceptions at every level just adds bloat to your code.
Given your example of UI--> Method1 -->Method2 --> Method3, I would make sure that the UI has a try/catch, but then none of the other methods should catch exceptions unless they can handle them without re-throwing. And even if they handle the exception, you should question whether that exception should happen in the first place. If you handle an exception and go about your merry way, then that exception is part of your normal process flow which is a serious code smell.
Here are my recommendations:
1) Put your exception handling code in all your UI events, and then have the actual action farmed off to some other method. Don't scatter exception handling code all over the place. It's clunky and makes the code hard to read.
protected void Button1_Click(object sender, EventArgs e) {
try {
DoSomething();
}
catch Exception e {
HandleError(e);
}
}
2) Don't do this. You'll lose your stack trace and the next developer who maintains your code will hunt you down.
try {
DoSomething();
}
catch Exception e {
throw e; // don't rethrow!!!
}
If you aren't going to handle the exception, don't catch it. Or, use a naked throw like this:
try {
DoSomething();
}
catch SomeException e {
HandleException(e);
}
catch {
throw ; // keep my stack trace.
}
3) Only throw exceptions in exceptional circumstances. Don't have try/catch blocks as part of your normal process flow.
4) If you're going to throw an exception, don't ever throw a System.Exception. Derive an exception object and throw it. I often just a generic BusinessException class. This way, users of your code can determine what exceptions you made up and which ones are system/environment related.
5) Throw ArgumentException, ArgumentNullException, or ArgumentOutOfRangeException if a method caller violates the contract (preconditions) of your method. If you catch one of these, it's a programming bug. A user should never see these exceptions.
If you remember that exceptions should be a very rare occurrence and that handling them is almost always a UI concern (so the bulk of your try/catch code should stay at the UI level) you will do well.
The basic rule is "Don't catch exceptions when you cannot handle it." So any unexpected exception should ultimately tell the user that something went wrong and shut down the application as gracefully as possible. Not shutting down the application is risky because the state might be corrupted and in turn corrupt information important to the user.
Robust applications are modular so that the application can recover without shutting down by stopping or restarting single components like services or plugins.
There are some cases where you might want to catch exceptions that you cannot handle but then the exception should either be re-thrown or a new exception should be thrown.
If you want to log exceptions you will catch, log and re-throw.
If you want to improve the error message you will catch, wrap in a new exception, and throw. For example you may want to wrap a generic FileNotFoundException when reading a file in a new exception with a more descriptive message telling the user what file could not be found.
Whatever you decide - be consistent. 30 days from now yourself (or another developer) will need to understand your code.
Also, as Scott Hanselman likes to quote on his podcast (and I think it might be in the Beautiful Code book) -
All problems in computer science can be solved by another level of indirection," is a famous quote attributed to Butler Lampson, the scientist who in 1972 envisioned the modern personal computer.
Throwing exceptions is expensive. And I like to have my business layer have its own specialized exception that only it can throw. That way it makes it easier to track it down. For example (off the top of my head since I do not have a C# compiler in front of me):
public class MyException : Exception
{
private MyException(Exception ex, string msg) {
this.Message = msg;
this.InnerException = ex;
}
internal static MyException GetSomethingBadHappened(Exception ex, string someInfo) {
return new MyException(ex, someInfo);
}
}
As a rule of thumb, exceptions should only be used for exceptional cases. That is, if you expect a method call to fail sometimes, you shouldn't use exceptions. If there are several possible outcomes, you could use an enumeration:
public enum AddCustomerResult
{
Success,
CustomerAlreadyExists,
CustomerPreviouslyRetired
}
You'd still get exceptions thrown, for database-unavailable errors, and the like; but you'd be testing for expected (albeit possibly rare) cases and indicating success/failure/etc as required.
This is just one technique that works well for me.
With exceptions you want to throw them in exceptional circumstances and anywhere where there is a layer traversal (my own convention, don't know how correct it is) you'd want to catch exceptions and rethrow with a custom wrapper class for that layer.
For example, in the DAL you'd want to catch exceptions and rethrow them as an inner exception on a DataAccessException perhaps; on a web service you'd wrap all your methods in exception handlers to rethrow with a MyWebServiceException. At the UI (which traverses the from inside the app to the user's screen) you'd want to catch, log and give them a nice message. As far as I can see no reason to catch or rethrow anywhere else.
It gives you an opportunity to hide the underlying exception (which you likely don't want to expose to the caller: e.g. database errors), log in centrally, and provide a common repeatable failure mode.
In your example, you'd catch exceptions at the UI level only; because if a UI operation fails you don't want the app to crash out with an unhandled exception.
Hope that helps!
When you design a multi-tier application, you should keep in mind that those tiers can be distributed, maybe hosted within different services on different machines, thus making it necessary to throw exceptions through remote boundaries which is not a very preferable way to do.
In such a case, catching them and just bubbling some sort of error message or code is a better way in my opinion. Additionally you should allways trace the exception when you catch it. Its always good to know whats going on in your application.
It almost always pays to separate exception handling and error reporting.
Catch exceptions where it makes sense to catch them, where you have enough context to know what exactly happened and how to recover - inside Method1..3. On catching known exception, push a record to the error log.
After completing operation or step UI level can check error log and present message of "Following errors occurred: ...".
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.