I have a lot of throw new NotImplementedExceptions() throughout my whole application. For now I want to silence them and to show a custom Message Dialog instead.
For catching them I'm using:
AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
if(eventArgs.Exception is NotImplementedException) {
return;
}
}
But the problem is that the exception is still threw.
How can I silence the throw when I catch this type of Exception within this piece of code?
It sounds like what you want to do is to do something nicer than exploding when a method you haven't implemented is invoked. I don't believe that is possible using AppDomain.FirstChanceException or the related UnhandledException. There's a good answer here that talks a bit about why simply suppressing exceptions is undesirable.
What you could do instead is use something besides raising an exception to mark methods as not implemented, like calling a helper that displays your message, when you haven't implemented something yet. You could use #if pragmas or the ConditionalAttribute to switch to actually throwing exceptions in non-DEBUG builds, if that's desirable. It's not that uncommon to use helpers for throwing exceptions anyway (see for example ThrowHelper in the BCL, or Throw in one of my own projects), as there are some benefits to avoiding throws.
This would look like:
public void UnImplementedMethod()
{
// rather than "throw new NotImplementedException("some message")"
MyHelper.NotImplemented("some message");
}
// ....
static class MyHelper
{
[Conditional("DEBUG")]
public static void NotImplemented(string msg)
{
#if DEBUG // can use whatever configuration parameter
MessageBox.Show("Not Implemented: "+ msg);
#else
throw new NotImplementedException(msg);
#endif
}
}
You can use generic parameters to handle unimplemented methods that have non-void returns, though you have to decide what to actually return if you don't throw an exception. With this pattern you can do whatever you'd like, and still easily find places that haven't been implemented.
Related
I would like to globally catch any exception that is thrown in my models and controllers because I assume following logic in every action method:
public ActionResult SomeActionMethod(SomeViewModel someViewModel)
{
try
{
// Do operation that may throw exception
}
catch (BLLException e)
{
ModelState.AddModelError("Error", e.Message);
}
catch (Exception e)
{
_log.Info(e);
RedirectToAction("ErrorPage", "ErrorControler");
}
return View(someViewModel);
}
A business logic layer will throw exceptions that user will be able to handle, and a message about that exception will be displayed to him. All other kinds of exception will be saved on server log and user will get an error page.
So since that logic will repeat in every controller I decided to move it to a global exception handler. But the question is: is it possible to go back from exception handler attribute to a line in action where it was thrown? I would like to achieve something like:
public class ExceptionGlobalHandler : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if( filterContext.Exception.GetType() == typeof(BLLException))
{
ModelState.AddModelError("Error", e.Message);
//Continue executing where excetpion was thrown
}
catch (filterContext.Exception.GetType() == typeof(BLLException))
{
_log.Info(e);
RedirectToAction("ErrorPage", "ErrorControler");
}
}
}
Is it clear solution, and what is the best way of doing it?. What do you think about that kind of approach?
Unfortunately I don't think there is a way in C# to do this, however you could build in some logic to do it for you.
In your Action's code, you'd just have to throw the exception later on, like record the exception internally and throw it only at the end of the method. For example:
public void SomeAction()
{
Exception innerEx;
try
{
//some code that may/may not cause exceptions.
}catch(Exception e)
{
innerEx = e;
}
//some more execution code, equivelent to your "carry on at line x"
throw innerEx;
}
Obviously this means your action's code would have to change, in addition to the wrapper you're using, but this, I think, is the unfortunate problem you have :(
TBH, I think you should rewrite the action's code, because a program that crashes should stop executing, and developers will generally put error checking code within their methods.
( to avoid confusion, I've been using Action to mean the System.Action class, NOT the mvc action class, because I know quite little about MVC, though I hope it makes sense anyway :P )
I would also say there may be something you've been missing - Have you considered seperating the methods you're calling into multiple separate calls? Thus, you could call them all at once, reacting appropriately on an Exception result from one of the calls, while the others will carry on happily.
Apparently, some exceptions may just get lost while using nested using statement. Consider this simple console app:
using System;
namespace ConsoleApplication
{
public class Throwing: IDisposable
{
int n;
public Throwing(int n)
{
this.n = n;
}
public void Dispose()
{
var e = new ApplicationException(String.Format("Throwing({0})", this.n));
Console.WriteLine("Throw: {0}", e.Message);
throw e;
}
}
class Program
{
static void DoWork()
{
// ...
using (var a = new Throwing(1))
{
// ...
using (var b = new Throwing(2))
{
// ...
using (var c = new Throwing(3))
{
// ...
}
}
}
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
// this doesn't get called
Console.WriteLine("UnhandledException:", e.ExceptionObject.ToString());
};
try
{
DoWork();
}
catch (Exception e)
{
// this handles Throwing(1) only
Console.WriteLine("Handle: {0}", e.Message);
}
Console.ReadLine();
}
}
}
Each instance of Throwing throws when it gets disposed of. AppDomain.CurrentDomain.UnhandledException never gets called.
The output:
Throw: Throwing(3)
Throw: Throwing(2)
Throw: Throwing(1)
Handle: Throwing(1)
I prefer to at least be able to log the missing Throwing(2) and Throwing(3). How do I do this, without resorting to a separate try/catch for each using (which would kinda kill the convenience of using)?
In real life, those objects are often instances of classes over which I have no control. They may or may not be throwing, but in case they do, I'd like to have an option to observe such exceptions.
This question came along while I was looking at reducing the level of nested using. There's a neat answer suggesting aggregating exceptions. It's interesting how this is different from the standard behavior of nested using statements.
[EDITED] This question appears to be closely related:
Should you implement IDisposable.Dispose() so that it never throws?
There's a code analyzer warning for this. CA1065, "Do not raise exceptions in unexpected locations". The Dispose() method is on that list. Also a strong warning in the Framework Design Guide, chapter 9.4.1:
AVOID throwing an exception from within Dispose(bool) except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.).
This goes wrong because the using statement calls Dispose() inside a finally block. An exception raised in a finally block can have an unpleasant side-effect, it replaces an active exception if the finally block was called while the stack is being unwound because of an exception. Exactly what you see happening here.
Repro code:
class Program {
static void Main(string[] args) {
try {
try {
throw new Exception("You won't see this");
}
finally {
throw new Exception("You'll see this");
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
What you are noticing is a fundamental problem in the design of Dispose and using, for which no nice solution as yet exists. IMHO the best design would be to have a version of Dispose which receives as an argument any exception which may be pending (or null, if none is pending), and can either log or encapsulate that exception if it needs to throw one of its own. Otherwise, if you have control of both the code which could cause an exception within the using as well as within the Dispose, you may be able to use some sort of outside data channel to let the Dispose know about the inner exception, but that's rather hokey.
It's too bad there's no proper language support for code associated with a finally block (either explicitly, or implicitly via using) to know whether the associated try completed properly and if not, what went wrong. The notion that Dispose should silently fail is IMHO very dangerous and wrongheaded. If an object encapsulates a file which is open for writing, and Dispose closes the file (a common pattern) and the data cannot be written, having the Dispose call return normally would lead the calling code to believe the data was written correctly, potentially allowing it to overwrite the only good backup. Further, if files are supposed to be closed explicitly and calling Dispose without closing a file should be considered an error, that would imply that Dispose should throw an exception if the guarded block would otherwise complete normally, but if the guarded block fails to call Close because an exception occurred first, having Dispose throw an exception would be very unhelpful.
If performance isn't critical, you could write a wrapper method in VB.NET which would accept two delegates (of types Action and an Action<Exception>), call the first within a try block, and then call the second in a finally block with the exception that occurred in the try block (if any). If the wrapper method was written in VB.NET, it could discover and report the exception that occurred without having to catch and rethrow it. Other patterns would be possible as well. Most usages of the wrapper would involve closures, which are icky, but the wrapper could at least achieve proper semantics.
An alternative wrapper design which would avoid closures, but would require that clients use it correctly and would provide little protection against incorrect usage would have a usage batter like:
var dispRes = new DisposeResult();
...
try
{
.. the following could be in some nested routine which took dispRes as a parameter
using (dispWrap = new DisposeWrap(dispRes, ... other disposable resources)
{
...
}
}
catch (...)
{
}
finally
{
}
if (dispRes.Exception != null)
... handle cleanup failures here
The problem with this approach is that there's no way to ensure that anyone will ever evaluate dispRes.Exception. One could use a finalizer to log cases where dispRes gets abandoned without ever having been examined, but there would be no way to distinguish cases where that occurred because an exception kicked code out beyond the if test, or because the programmer simply forgot the check.
PS--Another case where Dispose really should know whether exceptions occur is when IDisposable objects are used to wrap locks or other scopes where an object's invariants may temporarily be invalidated but are expected to be restored before code leaves the scope. If an exception occurs, code should often have no expectation of resolving the exception, but should nonetheless take action based upon it, leaving the lock neither held nor released but rather invalidated, so that any present or future attempt to acquire it will throw an exception. If there are no future attempts to acquire the lock or other resource, the fact that it is invalid should not disrupt system operation. If the resource is critically necessary to some part of the program, invalidating it will cause that part of the program to die while minimizing the damage it does to anything else. The only way I know to really implement this case with nice semantics is to use icky closures. Otherwise, the only alternative is to require explicit invalidate/validate calls and hope that any return statements within the part of the code where the resource is invalid are preceded by calls to validate.
Maybe some helper function that let you write code similar to using:
void UsingAndLog<T>(Func<T> creator, Action<T> action) where T:IDisposabe
{
T item = creator();
try
{
action(item);
}
finally
{
try { item.Dispose();}
catch(Exception ex)
{
// Log/pick which one to throw.
}
}
}
UsingAndLog(() => new FileStream(...), item =>
{
//code that you'd write inside using
item.Write(...);
});
Note that I'd probably not go this route and just let exceptions from Dispose to overwrite my exceptions from code inside normal using. If library throws from Dispose against strong recommendations not to do so there is a very good chance that it is not the only issue and usefulness of such library need to be reconsidered.
I've found a method using reflection (and got it's MethodInfo). How can I invoke it without getting TargetInvocationException when exceptions are thrown?
Update
I'm creating a command implementation where the commands are handled by classes which implemement
public interface ICommandHandler<T> where T : class, ICommand
{
public void Invoke(T command);
}
Since there is one dispatcher which takes care of find and map all handlers to the correct command I can't invoke the methods directly but by using reflection. Something like:
var handlerType = tyepof(IHandlerOf<>).MakeGenericType(command.GetType());
var method = handlerType.GetMethod("Invoke", new [] { command.GetType() });
method.Invoke(theHandler, new object[]{command});
It works fine, but I want all exceptions to get passed on to the code that invoked the command.
So that the caller can use:
try
{
_dispatcher.Invoke(new CreateUser("Jonas", "Gauffin"));
}
catch (SomeSpecificException err)
{
//handle it.
}
Instead of having to catch TargetInvocationException.
(I know that I can throw the inner exception, but that's pretty worthless since the stack trace is destroyed)
Update2
Here is a possible solution..
But it seems more like a hack. Aren't there a better solution? Maybe with expressions or something?
Create a Delegate from the MethodInfo (through one of the overloads of Delegate.CreateDelegate) and invoke that instead. This won't wrap any exception thrown by the method inside a TargetInvocationException like MethodInfo.Invoke does.
class Foo
{
static void ThrowingMethod()
{
throw new NotImplementedException();
}
static MethodInfo GetMethodInfo()
{
return typeof(Foo)
.GetMethod("ThrowingMethod", BindingFlags.NonPublic | BindingFlags.Static);
}
// Will throw a NotImplementedException
static void DelegateWay()
{
Action action = (Action)Delegate.CreateDelegate
(typeof(Action), GetMethodInfo());
action();
}
// Will throw a TargetInvocationException
// wrapping a NotImplementedException
static void MethodInfoWay()
{
GetMethodInfo().Invoke(null, null);
}
}
EDIT:
(As the OP has pointed out, DynamicInvoke won't work here since it wraps too)
Based on your update, I would just use dynamic:
((dynamic)theHandler).Invoke(command);
You can't. That's the specified way that exceptions are propagated by invoking a method via reflection. You can always catch TargetInvocationException and then throw the "inner" exception obtained via the InnerException property, if you want the effect to be the original exception being thrown.
(You'll lose the original stack trace, mind you. It's possible that there's a way to prevent that, but it's tricky. I believe there may be more support for this in .NET 4.5; I'm not sure.)
You can call Invoke on the mehtodinfo instance, but the first argument of the call is the target (The object that the method info belongs to). If you pass this and it has access to call it, you should not get the exception.
I'm refactoring a medium-sized WinForms application written by other developers and almost every method of every class is surrounded by a try-catch block. 99% of the time these catch blocks only log exceptions or cleanup resources and return error status.
I think it is obvious that this application lacks proper exception-handling mechanism and I'm planning to remove most try-catch blocks.
Is there any downside of doing so? How would you do this? I'm planning to:
To log exceptions appropriately and prevent them from propagating to the user, have an Application.ThreadException handler
For cases where there's a resource that needs cleanup, leave the try-catch block as it is
Update: Using using or try-finally blocks is a better way. Thanks for the responses.
In methods that "return-false-on-error", let the exception propagate and catch it in the caller instead
Any corrections/suggestions are welcome.
Edit: In the 3rd item, with "return-false-on-error" I meant methods like this:
bool MethodThatDoesSomething() {
try {
DoSomething(); // might throw IOException
} catch(Exception e) {
return false;
}
}
I'd like to rewrite this as:
void MethodThatDoesSomething() {
DoSomething(); // might throw IOException
}
// try-catch in the caller instead of checking MethodThatDoesSomething's return value
try {
MethodThatDoesSomething()
} catch(IOException e) {
HandleException(e);
}
"To log exceptions appropriately and prevent them from propagating to the user, have an Application.ThreadException handler"
Would you then be able to tell the user what happened? Would all exceptions end up there?
"For cases where there's a resource that needs cleanup, leave the try-catch block as it is"
You can use try-finally blocks as well if you wish to let the exception be handled elsewhere. Also consider using the using keyword on IDisposable resources.
"In methods that "return-false-on-error", let the exception propagate and catch it in the caller instead"
It depends on the method. Exceptions should occur only in exceptional situations. A FileNotFoundException is just weird for the FileExists() method to throw, but perfectly legal to be thrown by OpenFile().
For cleanup rather use try-finally or implement the IDisposable as suggested by Amittai. For methods that return bool on error rather try and return false if the condition is not met. Example.
bool ReturnFalseExample() {
try {
if (1 == 2) thow new InvalidArgumentException("1");
}catch(Exception e) {
//Log exception
return false;
}
Rather change to this.
bool ReturnFalseExample() {
if (1 == 2) {
//Log 1 != 2
return false;
}
If i'm not mistaken try catches are an expensive process and when possible you should try determine if condition is not met rather then just catching exceptions.
}
As an option for "return-false-on-error" you can clean up the code this way:
static class ErrorsHelper {
public static bool ErrorToBool(Action action) {
try {
action();
return true;
} catch (Exception ex) {
LogException(ex);
return false;
}
}
private static void LogException(Exception ex) {
throw new NotImplementedException();
}
}
and usage example:
static void Main(string[] args) {
if (!ErrorToBool(Method)) {
Console.WriteLine("failed");
} else if (!ErrorToBool(() => Method2(2))) {
Console.WriteLine("failed");
}
}
static void Method() {}
static void Method2(int agr) {}
The best is as said by others, do exception handling at 1 place. Its bad practice to conceal the raised exception rather than allowing to bubble up.
You should only handle only the exceptions that you are expecting, know how to handle and they are not corrupt the state of your application, otherwise let them throw.
A good approach to follow is to log the exception first, then Restart your application, just like what Microsoft did when office or visual studio crashing. To do so you have to handle the application domain unhanded exception, so:
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException;
//Add these two lines if you are using winforms
Application.ThreadException += OnApplicationThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
private void OnCurrentDomainUnhandledException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//Log error
//RestartTheApplication
}
Here an example on how to restart your application.
I think your strategy of removing try/catch block which just appear to do generic thoughtless logging is fine. Obviously leaving the cleanup code is necessary. However, I think more clarification is needed for your third point.
Return false on error methods are usually OK for things where exceptions are unavoidable, like a file operation in your example. Whereas I can see the benefit of removing exception handling code where it's just been put in thoughtlessly, I would consider carefully what benefit you get by pushing responsibility for handling an exception of this kind higher up in the call chain.
If the method is doing something very specific (it's not generic framework code), and you know which callers are using it, then I'd let it swallow the exception, leaving the callers free of exception handling duties. However, if it's something more generic and maybe more of a framework method, where you're not sure what code will be calling the method, I'd maybe let the exception propagate.
You may try to use AOP.
In AOP through PostSharp, for example, you can handle exceptions in one central place (piece of code) as an aspect.
Look at the examples in documentation to have an idea => Docs on Exception Handling with PostSharp.
we can remove try and catch by adding condition Like
string emailAddresses = #"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$";
if (!Regex.IsMatch(Email, emailAddresses))
{
throw new UserFriendlyException($"E-mail Address Is not Valid");
}**strong text**
In an application I work on, any business logic error causes an exception to be thrown, and the calling code handles the exception. This pattern is used throughout the application and works well.
I have a situation where I will be attempting to execute a number of business tasks from inside the business layer. The requirement for this is that a failure of one task should not cause the process to terminate. Other tasks should still be able to execute. In other words, this is not an atomic operation. The problem I have is that at the end of the operation, I wish to notify the calling code that an exception or exceptions did occur by throwing an exception. Consider the following psuedo-code snippet:
function DoTasks(MyTask[] taskList)
{
foreach(MyTask task in taskList)
{
try
{
DoTask(task);
}
catch(Exception ex)
{
log.add(ex);
}
}
//I want to throw something here if any exception occurred
}
What do I throw? I have encountered this pattern before in my career. In the past I have kept a list of all exceptions, then thrown an exception that contains all the caught exceptions. This doesn't seem like the most elegant approach. Its important to preserve as many details as possible from each exception to present to the calling code.
Thoughts?
Edit: The solution must be written in .Net 3.5. I cannot use any beta libraries, or the AggregateException in .Net 4.0 as mentioned by Bradley Grainger (below) would be a nice solution for collection exceptions to throw.
The Task Parallel Library extensions for .NET (which will become part of .NET 4.0) follow the pattern suggested in other answers: collecting all exceptions that have been thrown into an AggregateException class.
By always throwing the same type (whether there is one exception from the child work, or many), the calling code that handles the exception is easier to write.
In the .NET 4.0 CTP, AggregateException has a public constructor (that takes IEnumerable<Exception>); it may be a good choice for your application.
If you're targeting .NET 3.5, consider cloning the parts of the System.Threading.AggregateException class that you need in your own code, e.g., some of the constructors and the InnerExceptions property. (You can place your clone in the System.Threading namespace inside your assembly, which could cause confusion if you exposed it publicly, but will make upgrading to 4.0 easier later on.) When .NET 4.0 is released, you should be able to “upgrade” to the Framework type by deleting the source file containing your clone from your project, changing the project to target the new framework version, and rebuilding. Of course, if you do this, you need to carefully track changes to this class as Microsoft releases new CTPs, so that your code doesn't become incompatible. (For example, this seems like a useful general-purpose class, and they could move it from System.Threading to System.) In the worst case, you can just rename the type and move it back into your own namespace (this is very easy with most refactoring tools).
Two ways of the top of my head would be either make a custom exception and add the exceptions to this class and throw that the end :
public class TaskExceptionList : Exception
{
public List<Exception> TaskExceptions { get; set; }
public TaskExceptionList()
{
TaskExceptions = new List<Exception>();
}
}
public void DoTasks(MyTask[] taskList)
{
TaskExceptionList log = new TaskExceptionList();
foreach (MyTask task in taskList)
{
try
{
DoTask(task);
}
catch (Exception ex)
{
log.TaskExceptions.Add(ex);
}
}
if (log.TaskExceptions.Count > 0)
{
throw log;
}
}
or return true or false if the tasks failed and have a 'out List' variable.
public bool TryDoTasks(MyTask[] taskList, out List<Exception> exceptions)
{
exceptions = new List<Exception>();
foreach (MyTask task in taskList)
{
try
{
DoTask(task);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
if (exceptions.Count > 0)
{
return false;
}
else
{
exceptions = null;
return true;
}
}
You could create a custom Exception that itself has a collection of Exceptions. Then, in your Catch block, just add it to that collection. At the end of your process, check if the Exception count is > 0, then throw your custom Exception.
You might want to use a BackgroundWorker to do this for you. It automatically captures and presents any exceptions when completed, which you could then throw or log or do whatever with. Also, you get the benefit of multithreading.
The BackgroundWorker is a nice wrapper around delegate's asynchronous programming model.
No super-elegant solution here but a few ideas:
Pass an error-handler function as argument to DoTasks so the user can decide whether to continue
Use tracing to log errors as they occur
Concatenate the messages from the other exceptions in the exception bundle's message