Some times in C# I would like to throw an exception that cannot be handled. An escalated exception that results in the process being stopped. Is this possible?
You could do something like:
class BadassException : Exception
{
public BadassException(string message)
{
Environment.FailFast(message);
}
}
...
throw new BadassException("Erk!!!");
How about simply closing the process like this:
Process.GetCurrentProcess().Close();
If you don't want an exception to be handled, don't handle it.
That's not an exception, that's an atomic bomb.
Seriously though, there are better ways of handling this scenario. If you're looking to terminate your process look at options like Application.Exit.
It's not really possible because every exception must inherit from the Exception base class, and you can do a catch(Exception).
However, as others have pointed out, you can fail fast. You can also throw exceptions that cannot be caught specifically, like so:
public class MyLibraryClass
{
private class MyException : Exception { ... }
public void MyMethod() { throw new MyException(); }
}
Then the caller cannot do a catch(MyException exc), only a catch(Exception exc). But still, that means the exception can be caught.
Any exception that is not handled will stop your application. Usually applications have an application or top level exception handler that catches any unhandled exceptions, does any data maintenance and shuts down the application gracefully.
In your case, I think the best approach is to create a new exception that derives from exception class called something like StopApplicationException.
Then whenever you need to stop your application, throw this type of exception. In your catch block further up the call stack:
catch (StopApplicationException)
{
//Stop your application
}
catch (ArgumentNullException)
{
//Null Exception Logic goes here...
}
catch ...And so forth
Related
I have some code that currently looks somewhat like this:
public void MainFunction()
{
try
{
SomeProblemFunction();
}
catch
{
AllFineFunction();
}
}
private void SomeProblemFunction() { ... }
private void AllFineFunction() { ... }
As you can see, I'm currently wrapping the call to SomeProblemFunction around a try statement because that function could fail (it relies on an outside web service call).
My question is this: should the try statement be a) outside the problem function (like I have it now) or b) inside the problem function?
Thanks.
Typically you want to allow your exceptions propagate up to your application boundaries. You're only going to want to do one of a few things with your exception:
Wrap it
Replace it
Let it propagate
Update
From your question it seems that you are looking for a fault tolerant solution for your web service calls. This is a more complex problem than simply "where do I put my try-catch?" You would still place your exception handling at the application boundary, but there you would implement your fault tolerance strategy. This would need to have many considerations, including asynchronously calling your web service, number of retry attempts, etc. I would suggest doing a search for web service fault tolerance.
What you have is correct; see the MSDN example:
public class ThrowTestB
{
static void Main()
{
try
{
// TryCast produces an unhandled exception.
TryCast();
}
catch (Exception ex)
{
// Catch the exception that is unhandled in TryCast.
Console.WriteLine
("Catching the {0} exception triggers the finally block.",
ex.GetType());
// Restore the original unhandled exception. You might not
// know what exception to expect, or how to handle it, so pass
// it on.
throw;
}
}
public static void TryCast()
{
int i = 123;
string s = "Some string";
object obj = s;
try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;
// The following statement is not run.
Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
// Report that the finally block is run, and show that the value of
// i has not been changed.
Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
}
}
// Output:
// In the finally block in TryCast, i = 123.
// Catching the System.InvalidCastException exception triggers the finally block.
// Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}
As a rule of thumb I try and build code that focuses try catches to the exact spot the problem may occur.
That said both of your solutions are correct.
If it were my code I would do this
public void MainFunction()
{
try
{
SomeProblemFunction();
}
catch(Exception e)
{
Messagebox.Show(e.Message);
}
}
private void SomeProblemFunction() {
try{
web call
}
catch{
throw a specific exception related to this spot
}
}
private void AllFineFunction() { ... }
With this method you can easily create applications that handle a slew of very accurate exceptions
A fine question, I think. I'll attempt an answer.
If you want to recover within SomeProblemFunction, then it would make perfect sense to move the try...catch inside of that method. If, however, you are comfortable saying that if anything fails in SomeProblemFunction, then the whole thing is a failure, then keep it as you have it now and recover in (or throw from) MainFunction.
Thanks to the comment below, I'm adding some clarity. Depending on the specific exception that is being thrown within SomeProblemFunction, you may not have the ability to recover within that method. If you have a mixture of recoverable and non-recoverable, then it would be prudent to have the try...catch in both places.
The most important thing is that you NEVER catch an exception from which you cannot recover without throwing it on after doing your thing. It's tempting to add big broad catches (catch (Exception)) to avoid your app crashing during development, but it is never worth it. If those things make it into your production code, you've introduced a problem-solving and debugging nightmare.
In my opinion, there is no straight answer for this. The try catch is used to handle the exceptions that may occur. If your exception handling code is going in the main function then you should have the try catch in the main function. If your exception handling code in the problem function then you should add it to the problem function.
My preference though is to put it in both functions. If you put the try catch in the problem function, you can throw the exception and catch it in the main function. This always appear to other developers that the exception was thought of in that function and not missed handling it by mistake.
This depends on how severe this web service call failure would be.
Is it a failure that would prevent further processing of your code to run? If so, have no try/catch here, allowing it to propagate up to the guy who needs to know that this web service call failed. Optionally, you could still catch and throw a new exception with some more meaningful Exception type/ details.
Do you simply just want to re-try the web service call again if it doesn't work? IF so, then you have the try in the correct place; you just need to add a loop.
Is it not a big deal if this web service call fails? e.g. - will the rest of your code work OK? (I've found this to be uncommon). If so, leave the try/catch where it is, and log the error somewhere so that you're alerted.
I have a code that looks like this (sorry for the Java bracket style):
class SomeClass {
public static void doSomethingRisky() {
try {
SomeRiskyFunction();
} catch (Exception e) {
throw e;
}
}
}
class MainClass {
public void callSomethingRisky() {
try {
SomeClass.doSomethingRisky();
} catch (Exception e) {
FinallyHandleTheException(e);
}
}
}
Basically, SomeClass will be a library and I want to design it so that all exceptions will be handled by the calling program (who may or may not choose to display a message about the exception).
My question is about the use of try/catch&throw in the doSomethingRisky() from SomeClass. Is it redundant or is it necessary? I mean, if I leave it off and the function does encounter an Exception during runtime, will it crash the program because nothing catches the Exception inside THAT function, or does it still pass it to the caller (callSomethingRisky()) where it is gracefully handled?
Same question for Java. Thanks!
The try/catch with throw e; in doSomethingRisky does exactly one thing: it destroys the stack-trace information. That probably isn't what you wanted, so the try/catch should be removed - it will already bubble-up as expected.
For info, if it was just throw; (rather than throw e;) then it would merely be redundant, rather than destructive.
It will pass to the caller in both ways.
One of the uses of the construct you show above is to log the exception in the procedure, but still throw it so somewhere up the call stack a catch can handle the exception.
One thing to keep in mind, use throw in this situation instead of throw e to avoid loosing stack trace information.
In your case it is redundant. Often developers will add more information to the exception, or create a new exception with the original exception embedded as an inner exception. But to simply catch and rethrow is redundant.
Can I do this in a c# class library to handle exceptions that may occur during the execution of a class library code itself? I'm new in writing class libraries and exception handling within it. Please advice.
private void MethodName(String text)
{
try
{
..............
..............
..............
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
I've searched in google and stackoverflow, but did not find any article whether I'm allowed to handle exceptions in class libraries this way or if it is not a recommended way to do it. But it works. May be a dumb question, but I have this doubt.
Thanks.
Yes you can do that, but in general you should only catch exceptions if you are going to do something with it - i.e. swallow it or add value to it (by transforming, wrapping or logging it).
Using your example method, you should throw an exception if text is null and your method expects a value. Other than that you should let exceptions bubble out for the caller to handle unless you are going to do something with it, or it is an expected exception that you intend to suppress.
You also shouldn't throw a new exception, instead just use the throw keyword to rethrow the current exception:
catch (Exception ex)
{
//do something
throw;
}
In my current project, i am interacting with some 3rd party middleware that throws many different types of exceptions (around 10 exceptions or more).
My library that is using the 3rd party has a few methods, each one interacts with the 3rd party, however needs to be protected from the same set of 10 or more exceptions.
What i currently have is something like this in every method of my library:
try
{
// some code
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}
The number of exceptions may increase as well.
How can i reduce the code duplication and uniformly handle all exceptions in a single place?
suppose that the handling in each method in my code is the same.
I would start by catching the base Exception type and then filtering with a white-list:
try
{
// Code that might throw.
}
catch (Exception e)
{
if(e is Exception1 || e is Exception2 || e is ExceptionN)
{
// Common handling code here.
}
else throw; // Can't handle, rethrow.
}
Now if you want to generalize the filter, you can write an extension:
public static bool IsMyCustomException(this Exception e)
{
return e is Exception1 || e is Exception2 || e is ExceptionN;
}
and then you can just use:
if(e.IsMyCustomException())
{
// Common handling code here.
}
else throw;
You can generalize the handler with a simple method:
private void HandleCustomException(Exception e)
{
// Common handling code here.
}
If you want to generalize the entire try-catch block, you're probably best off injecting a delegate into a method that wraps the operation, as mentioned by #vc 74.
You can either use a global exception handler, the implementation depends on your project type (ASP.net -> global.asax, WPF -> App.xaml...)
Or use something like the following :
private static void HandleExceptions(Action action)
{
try
{
action();
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}
}
which can be invoked the following way:
HandleExceptions(() => Console.WriteLine("Hi there!"));
If an exception was thrown during the Console.WriteLine execution, it would then be handled by your exception handling logic
Note that the code to execute might also modify external values:
int x = 2;
HandleExceptions(() => x = 2 * x);
If you prefer anonymous methods:
var x = 2;
HandleExceptions(delegate()
{
x = x * 2;
});
I recommend using the Enterprise Library 5.0 Exception handling block. Basically, you define multiple exception types, categories and exception handlers that handle specific exception types. Ideally, you would define the exception type, hook it up to a formatter and then report the exception using the Logging block.
You can read all about it here...
how about use one function to handle these Exceptions:
try
{
//Some code here
}
catch(Exception e)
{
if(!ErrorHandler(e))
return null; //unhandled situation
}
private bool ErrorHandler(Exception e)
{
switch(e)
{
case Exception1:
//Handle the exception type here
return true;
case Exception2:
//Handle another exception type here
return true;
}
return false;
}
There are some semantic differences between catching and rethrowing an exception, versus not catching it. Exception filters are therefore very useful, since they allow one to e.g. "Catch Ex As Exception When IsNiceException(Ex)". Unfortunately, the only way to use them within a C# program is to use a DLL to wrap the necessary functionality (the DLL itself could be written in vb or some other language). A typical pattern might be something like:
TryWhenCatchFinally(
() => {trycode;},
(Exception ex) => {codeWhichReturnsTrueForExceptionsWorthCatching;},
(Exception ex) => {codeToHandleException;},
(ExceptionStatus status, Exception ex) => {finallyCode;});
The ExceptionStatus parameter to the "finally" code would be an enumeration saying whether (1) no exception occurred, (2) an exception occurred, but was handled, (3) an exception occurred and was handled, but another exception was thrown, or (4) an exception occurred but CodeWhichReturnsTrueForExceptionsWorthCatching returned false; (5) an exception occurred which was not handled within trycode, nor handled by this block, but trycode completed anyhow (a rare situation, but there are ways it can happen). The Ex parameter will null in the first case, and contain the appropriate exception in others--potentially useful information to have if an exception occurs while processing the finally block (stifling an exception that occurs in a finally block may be bad, but if the earlier exception isn't logged or lost before the new exception escapes, all data from the earlier exception will generally be lost; if the same condition which caused the earlier exception caused the later one, the earlier exception might have more useful information about what went wrong).
BTW, a few notes with this pattern:
The code that decides whether to catch an exception will run before nested finally blocks execute; it may capture useful data for logging (the fact that finally blocks haven't run may make available for logging information which would get destroyed by nested finally blocks), but actual cleanup should typically be done after finally blocks have run.
At present, it seems like exceptions that would escape from filters get stifled, but I'm not sure that behavior is guaranteed. Operations which might leak exceptions should probably not be done within filters.
If the "trycode" contains a try-finally block that's nested within a try-catch block, an exception which occurs in the "try" part of that try-finally block is not handled by the TryCatchWhenFamily nor any nested scope, but is handled by an outer block, and the processing of the inner try-finally block throws an exception which the inner try-catch block handles, the exception which the outer block had decided it was going to catch might disappear without ever being caught. If the TryWhenCatchFinally method is coded to detect this condition, it could let its finally block code know about that (the finally block may or may not want to do anything about the condition, but it should probably at minimum be logged).
What are your thoughts on code that looks like this:
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
throw;
}
}
The problem I see is the actual error is not handled, just throwing the exception in a different place. I find it more difficult to debug because i don't get a line number where the actual problem is.
So my question is why would this be good?
---- EDIT ----
From the answers it looks like most people are saying it's pointless to do this with no custom or specific exceptions being caught. That's what i wanted comments on, when no specific exception is being caught. I can see the point of actually doing something with a caught exception, just not the way this code is.
Depending on what quality you are looking at it is not throwing the exception in a different place. "throw" without a target rethrows the exception which is very different from throwing an exception. Primarily a rethrow does not reset the stack trace.
In this particular sample, the catch is pointless because it doesn't do anything. The exception is happily rethrown and it's almost as if the try/catch didn't exist.
I think the construction should be used for handling the exceptions you know you will be throwing inside your code; if other exception is raised, then just rethrow.
Take into account that
throw;
is different than
throw ex;
throw ex will truncate the stack to the new point of throwing, losing valuable info about the exception.
public void doSomething()
{
try
{
// actual code goes here
}
catch (EspecificException ex)
{
HandleException(ex);
}
catch (Exception ex)
{
throw;
}
}
It wouldn't be, ideally the catch block would do some handling, and then rethrow, e.g.,
try
{
//do something
}
catch (Exception ex)
{
DoSomething(ex); //handle the exception
throw;
}
Of course the re-throw will be useful if you want to do some further handling in the upper tiers of the code.
Doing something like that is fairly meaningless, and in general I try not to go down the road of doing meaningless things ;)
For the most part, I believe in catching specific types of exceptions that you know how to handle, even if that only means creating your own exception with more information and using the caught exception as the InnerException.
Sometimes this is appropriate - when you're going to handle the exception higher up in the call stack. However, you'd need to do something in that catch block other than just re-throw for it to make sense, e.g. log the error:
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
LogException (ex); // Log error...
throw;
}
}
I don't think just rethrowing the error would be useful. Unless you don't really care about the error in the first place.
I think it would be better to actually do something in the catch.
You can check the MSDN Exception Handling Guide.
I've seen instances where generic exceptions are caught like this and then re-packed in a custom Exception Object.
The difference between that and what you're saying is that those custom Exception objects hold MORE information about the actual exception that happened, not less.
Well for starters I'd simply do
catch
{
throw;
}
but basically if you were trapping multiple types of exceptions you may want to handle some locally and others back up the stack.
e.g.
catch(SQLException sex) //haha
{
DoStuff(sex);
}
catch
{
throw;
}
Depends on what you mean by "looks like this", and if there is nothing else in the catch block but a rethrow... if that's the case the try catch is pointless, except, as you say, to obfuscate where the exception occurred. But if you need to do something right there, where the error occurred, but wish to handle the exception furthur up the stack, this might be appropriate. But then, the catch would be for the specific exception you are handl;ing, not for any Exception
Generally having exception handling blocks that don't do anything isn't good at all, for the simple reason that it prevents the .Net Virtual Machine from inlining your methods when performance optimising your code.
For a full article on why see "Release IS NOT Debug: 64bit Optimizations and C# Method Inlining in Release Build Call Stacks" by Scott Hanselman