I thought I could catch an exception thrown by another class in my project, but I must be doing it wrong. In the first class, I'm surrounding my call to the other class with a try/catch block:
try
{
ImportPowerPoint.CreateTitle(textBoxPpt.Text, textBoxPkg.Text);
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message, "ERROR",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
In the second class, this is where I'm throwing the exception:
if (!_layoutMap[(int)Layouts.A].ContainsValue(Fields.Title))
throw new FormatException("Standard (A) Layout does not contain a title.");
if (!_layoutMap[(int)Layouts.A].ContainsValue(Fields.Txt1))
throw new FormatException("Standard (A) Layout does not contain a txt1.");
if (!_layoutMap[(int)Layouts.A].ContainsValue(Fields.Prompt))
throw new FormatException("Standard (A) Layout does not contain a prompt.");
When I run the program, it breaks immediately where the exception is thrown, instead of displaying the error window that I defined in the try/catch block. Am I not handling this try/catch correctly?
For clarification, I'm forcing the exception to occur by removing certain pieces from the PowerPoint that I'm parsing. When the program fails, for instance, because I removed the Title Field, the exception thrown is of type FormatException. Shouldn't my catch in the calling class handle this?
EDIT: I think I may have found out something that is causing this to happen. The exception being thrown is in another thread. So, since it's in another thread, could this mean that this is why my try/catch isn't catching the exception?
It is breaking in the IDE to notify that the exception is thrown. If you press F5 again to continue running, your catch handler should be hit.
There is nothing class-related about exceptions. Your calling code (ImportPowerPoint.CreateTitle(...);) should be able to catch exceptions thrown by CreateTitle().
See if your Visual Studio is configured to catch all exceptions (opposed to catching only unhandled ones):
Go to the 'Debug' menu
Select 'Exceptions...'
Uncheck check boxes under the 'Thrown' column
You would typically want the IDE to catch unhandled exceptions, so I would keep the other column checked.
The problem here appears to be because this is a multithreaded program. I'm looking at using the AppDomain.UnhandledException Event to handle my exceptions.
Related
I have there piece of code
//Code 1 Code 2 Code 3
try try try
{ { {
//Exp occur //Exp occur //Exp occur
} } }
catch (Exception e) catch (Exception) catch
{ { {
//Handle exp //Handle exp //Handle exp
} } }
What is the difference between all of three codes
P.S. I'm new to C# and as far as Java or Objective-C is concerned this syntax throws error
Code 1
Its catching Exception in an object e which can be later used for exception handling. For example you can log the Message property or view stack trace using e.Message or e.StackTrace
Code 2
You are catching all the exception of the base type Exception but since you don't have any object related to it, you can only throw that exception so that it can bubble up or you may ignore the exception. If in that code you had :
catch(InvalidCastException)
Then all the InvalidCastException will be handled in the block without the exception object
Code 3
You are catching all type of exceptions irrespective of their type, which is similar to your code 2 with base class Exception
try-catch - MSDN
Although the catch clause can be used without arguments to catch any
type of exception, this usage is not recommended. In general, you
should only catch those exceptions that you know how to recover from.
Its always better if you catch specific exceptions before catching the base one. Something like.
try
{
}
catch(InvalidCastException ex)
{
}
catch(Exception ex)
{
}
try - catch - MSDN
It is possible to use more than one specific catch clause in the same
try-catch statement. In this case, the order of the catch clauses is
important because the catch clauses are examined in order. Catch the
more specific exceptions before the less specific ones. The compiler
produces an error if you order your catch blocks so that a later block
can never be reached.
Code 1 - fairly normal catch, hopefully doesn't need explanation
Code 2 - You want to execute a particular piece of code when a particular exception occurs, but you have no intention of actually interacting with the exception object. Should almost always have a throw; statement at the end, so that someone else higher up the stack who does care can catch it.
Code 3 - You want the code to execute for any exception(*) (except for any caught by earlier catch clauses of the same try). Again, should almost always include a throw; so that higher code can catch and actually process the exception.
At some level (possibly just at the top level, in the unhandled exception handlers for whatever environment you're in), something ought to be inspecting the exception object and probably logging it (if possible).
Here if you want to use the variable 'e' for getting the Exception message, Line or type.
//Code 1
try
{
//Exp occur
}
catch (Exception e)
{
//Handle exp
}
Below code for getting particular type of Exception and not dealing with Exception variable.
//Code 2
try
{
//Exp occur
}
catch (Exception)
{
//Handle exp
}
Below code catching all types of exceptions.
//Code 3
try
{
//Exp occur
}
catch
{
//Handle exp
}
if you plan to actually use the exception object, to log its properties to a log file or to show a message box or to throw another kind of exception and pass the current exception to its constructor, then you must use the first of the three (most left one).
in general the most used approach is the first one anyway, if you want to handle different kind of exceptions separately you can have multiple catch blocks starting with the most specialized on top and have the one you wrote at the bottom so that all exceptions not already handled will end in the generic catch block.
Nothing. They all catch EVERY exception that could possibly occur (by catching base type Exception or just any). This is typically frowned upon, for good reason. You should catch specific exceptions in the order you expect, and then if you do want to catch all exceptions catch Exception at the end.
try
{
}
catch (MyCustomException)
{
// do something for your custom exception
}
catch (Exception)
{
// do something for everything else
}
When you specify a variable for your exception such as catch (Exception e) you will have access to the stack trace (and other exception information) via e.Property or simply e.ToString() for the full message. It's also best practice to throw the exception when caught (well, unless you want to suppress it at this level and not allow your calling code to see the exception) so it bubbles up and you preserve the stack trace:
catch (Exception e)
{
// do something with e
throw;
}
Code 1 catches every exception (in your case!) and declares it, so you can use it later e.g. for Error-Messages.
MessageBox.Show(e.Message);
Code 2 also catches every exception (in your case!), but you can't use it, because it is not declared.
These two methods are not designed for that, they're designed to catch specific or custom exceptions.
try
{
//mycode
}catch(MyException myExc)
{
//TODO HERE
Console.Write(myExc.Message);
}
The third one catches all exceptions. Because there is no definition.
Take a look at: http://msdn.microsoft.com/de-de/library/0yd65esw%28v=vs.80%29.aspx
to learn more about exceptions in C#.
Differences:
Declaring Exception Parameter ex allows you to access the Exception object, in order to see and work with its properties, fields, methods and the like. This "ex" variable works like any parameter in any method.
Declaring Exception Type without parameter ex allows you to separate several "catch" areas for different types of exception. It is useless, and functionally equivalent to code sample 3 as you define it here, but if you need to do different actions depending on the type of the exception, and you do not need to access the exception object (you only need to know the type of the exception), then this is your way to go.
Untyped Catch Exception Handler allows you to add a fallback for any Exception that might be thrown, whatever its type. Since it is not parameterized, however, you won't have access to the Exception object's properties or methods. Both code sample 2 and code sample 3 therefore are equivalent.
Example:
try{ // code that throws exception }
catch(TypeException ex)
{
// code to handle exceptions of type TypeException
// I can access ex parameter, for example to show its Message property
MessageBox.Show(ex.Message);
}
catch(OtherTypeException)
{
// code to handle exceptions of type OtherTypeException
// I cannot access the ex parameter since it is not declared, but I know
// the exact type of the exception
MessageBox.Show("There was an exception of Other Type");
}
catch
{
// code to handle any other exception
// this is functionally equivalent to catch(Exception) since all typed exceptions
// inherit from the base type Exception
MessageBox.Show("An unknown exception has been thrown.");
}
...
This is my current exception handling code.
Take especial note of the line throw e; marked with ***.
try
{
//some code that could cause exception
}
catch (FaultException e) //first catch a particular type of exception only
{
if (Regex.IsMatch(e.Message, "something")) //satisfying a particular condition
{
Console.WriteLine("Particular exception occurred.");
return;
}
else
throw e; // <-- *** Problem! Not getting caught by the "catch" below.
}
catch (Exception e) //catch all other exceptions
{
Console.WriteLine("General exception ocurred");
return;
}
The problem is this: If the throw e; // <-- *** occurs, it is not getting caught by the final catch. Instead, the app just crashes as if the exception was not handled.
How can this be fixed in the simplest possible way?
You see in the first catch that I'm only interested in actually handling FaultException exceptions satisfying a particular condition, but leave all others (both FaultException exceptions not satisfying the condition and exceptions that are not FaultException) to the final catch. Unfortunately, this is not working properly.
I'm on .NET 4.
You don't fully understand the try/catch syntax. You can attach multiple catches to a single try - the one that matches most closely is the one that will be selected. In this case, FaultException's catch will fire, and then the more general Exception one will never be called, because the exception has already been handled.
What you need to do is wrap the entire try/catch in another try/catch specifically for the more general Exception case, if you always want to handle that; either that or rework your logic. (For instance, you could just simplify it to be an Exception catch and then check if it's a FaultException.)
Only one catch block is executed per try block.
I would rewrite the catch block as:
catch (Exception e)
{
if (e is FaultException && Regex.IsMatch(e.Message, "something"))
{
....
}
else // all other exceptions
{
....
}
}
The throw e will never be caught by exception catches at the same level.
A throw inside of a catch, will always throw to the invoker of the method.
Also, its recommended that if you want to re-throw do throw instead of throw e. The first case preserves the call-stack.
If you throw an exception within a catch block, it won't be caught within the same try-catch.
You could repeat in the else condition what you're doing in the other catch block (not too bad in this specific case).
I want to catch all exceptions raised (handled or unhandled) to log them. for unhandled i use ThreadExceptionEventHandler and UnhandledExceptionEventHandler but i want to catch and exceptions that are in try catch block with or without (Exception e). It's possible to inherit the exceptions class to create a general event?
Starting from Windows XP you can get notified about every raised exception, even before it's known to be handled or not.
This is available via so-called "vectored" exception handling, which is actually a little addition to the standard structured exception handling.
Call AddVectoredExceptionHandler to add your own handler. You'll get called right after the exception is raised, either by explicit throw/__CxxThrowException/RaiseException or implicitly by the processor (access violation or etc.)
You can log the exception in your handler (produce stack dump for instance), and return EXCEPTION_CONTINUE_SEARCH.
Inheriting from Exception to provide your own Exception class would work fine for exceptions you generate in your code, and you could use the inner exception constructor to carry built in exceptions up the chain.
If you were goig to try that, you'd need to replace all of your exception handling code, and probably add a chunk more as well. I don't think it'd be substantially better than Peter McG's approach, but it might allow you different options when preserving & examining the original exceptions and re-throwing, for example keeping a record of whether it has already been logged lower down the chain.
Just to be explicit, it is possible to use:
catch (Exception e)
{
log(e);
throw;
}
which will rethrow the original exception.
Sounds like you've got the Unhandled Exceptions as covered as possible, for handled exceptions can't you just eventually...
catch (Exception e) {}
and call the same logging function with the instance.
If not and you really must have some instances where you have a catch but without catching an instance you can use...
catch { throw; }
to re-throw the exception to be eventually caught and logged as an un-handled exception.
C++ allows for catch(...) which catches all exceptions but doesn't really allow to analyze them in depth. (see using catch(...) (ellipsis) for post-mortem analysis )
I'm not sure if it will work in C# though.
No, thats not possible.
The only way this would be possible is using the debugging APIs (the managed version is named mdbg)
There's no way to catch an already caught exception except, may be, working with AddVectoredExceptionHandler.
Having said that, you can use a catch-and-rethrow approach:
catch(Exception e) {
Logger.Log(e);
throw;
}
or
catch(Exception e) {
bool rethrow = LoggerStrategy.Log(e);
if(rethrow) { throw; }
}
Better still, use the Logging Application Block.
I read a lot about how bad catching base Exceptions is and I have to confess that I did it also:
try{
...
}
catch (Exception exception){
MessageBox.Show(exception.Message, "Error!");
MyLogger.Log(exception.Message);
}
Now I would like to do it right and have some questions about it:
Which exceptions should I catch (for example FileNotExists for file manipulation, but what for TableAdapter or ReportClass (CrystalReports))
Where can I see a list of exceptions, that an objects can throw (for example TableAdapter)
Where in Windows Forms Application can I set a static method, which will log any exception to a file for example
Any other suggestions?
Catch whichever exceptions you can reasonably handle. For example, if you're trying to open a file for writing, you should expect that maybe the file is marked read-only, so that would throw an exception. But in the same situation you wouldn't try to catch a null argument exception, because that would be due to programmer error.
They should be found in the function reference in MSDN (you'll have to look it up on each one). For user-defined functions, you'll have to go digging, unless there is additional documentation or summary commentary.
3, 4. Consider using a logging library for .NET
I have one thing to add. If you just want to log an exception without affecting program flow you can always do this:
try
{
...
}
catch (Exception exception)
{
MyLogger.Log(exception.Message);
throw;
}
That's up to you to decide which exceptions your application logic can reasonably expect to recover from.
Exceptions are thrown by method invocations, not objects. In Visual Studio, Intellisense explanations will tell you which exceptions are thrown by an object (provided that the XML documentation describes which exceptions a method throws.
Rather than use a static method, respond to the Application.ThreadException event. The link provided has examples.
MSDN
You can set an event for unhandled exceptions in application events file
(got a VB sample here but i hope you get the point)
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
End Sub
You can find the application events in the options of you project.
You should only catch exceptions you can do something about, really.
That's the rule of thumb. I typically have a try/catch around my Program.Main just in case an exception bubbles right to the top and needs logging. You can also handle the CurrentDomain_UnhandledException event, in case exceptions are thrown in other threads than the UI thread (assuming you are multithreading).
In response to "4. Any other suggestions?":
In your example code, a message box is displayed before logging the exception. I would recommend logging the exception before displaying the message, just in case the user sees the error message, panics, and goes on vacation without clicking "OK". It's a minor thing, but message boxes block the program indefinitely and should be used with discretion!
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