I had an exception in some code today: "A [some exception] was unhandled."
However, this code was clearly inside the "try" block of a "try/catch" structure.
What am I missing here?
Update: It's C#
Update: Oh, forget it. It turns out the specific mechanism of error is that I'm an idiot. There's no fix for this.
Does the catch statement specify a specific type of exception?
If it does, it will only catch that type of exception.
Were you running in a debugger with "break on exceptions"/"break on thrown" switched on? In this case you'll see the exception before it is passed to the try/catch.
Unmanaged exceptions will not be caught by catch(Exception e),you can try a
try
{
}
catch
{
}
instead of
try
{
}
catch (Exception e)
{
}
some problems caused by Recursion such as StackOverFlow exceptions and the like will throw inside of try...catch blocks because they are not actually thrown from any particular line of code within the block, but rather by the CLR. This is also true for Memory out of range exceptions and other problems that aren't the direct result of any one line of code.
Maybe you're talking about something like this:
I have 10 dollars that says its a ThreadAbortException or some other self-throwing exception. If that is the case you must catch the exception twice.
Without knowing the language it's difficult to say, but many languages have the concept of exceptions that cannot be caught - for example in .NET, OutOfMemoryException and ExecutionEngineException (amongst others) cannot be caught, since they are essentially non-recoverable.
Related
Is a simple question that seeks a simple answer. No code is needed as a demonstration. When i call a function it returns an exception and the whole function stops. How can I ignore the exception and continue the function?
You cannot ignore the exception.
If you do not catch it then the exception will propogate up the call stack until somebody does catch it and handle it, or it reaches the top of the call stack and your program halts.
To avoid that, you simply catch the exception and decide how to handle it. If handling it means doing nothing it then simply ... do nothing when you catch the exception:
try
{
SomeFnWhichThrowsAnException();
}
catch
{
// NO-OP
}
The // NO-OP comment (short of "No-Operation") is an indicator I use to indicate that the "handling" of the exception is to deliberately do nothing, to avoid any potential misunderstanding on the part of anyone reading suh code in the future and interpreting an empty catch block as an error or an oversight.
It should be mentioned that even with a comment and a "good reason" to do nothing in response to an exception, this is highly suspect and is a very bad code smell.
It may be more common to specifically ignore very specific exceptions or to do so only in specific circumstances, but to ignore every possible exception is highly unadvisable (consider that this will include exceptions such as stack overflows or out of memory conditions etc).
try
{
MyFunctionThatErrors();
}
catch{}
A try...catch statement should do this job:
try {
// your code that might throw an exception here
} catch {
}
// code here will execute even if there is an exception
However, try...catch statements are not designed to act as a flow control statement. You shouldn't just ignore the exception without a good reason. You should avoid the exception being thrown in the first place.
For example, Convert.ToInt32 can throw an exception if the string parameter is in the wrong format. You shouldn't use try...catch here as a way to detect invalid user input. You should check whether the input is valid using some other method, like regex for example.
You can use a try {..} catch {..} statement.
Here's the reference docs.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch
What is the difference between:
catch
{
MessageBox.Show("Error.");
}
and:
catch (Exception ex)
{
MessageBox.Show("Error.");
//we never use ex, so is it better to use catch without arguments?
}
As of .NET 2, if you don't tweak the configuration? Nothing.
Before then, or with some config tweak I can't remember precisely, there was the possibility of an exception being thrown from unmanaged code which didn't get converted into an Exception-compatible object.
Note that there's another option in between, where you specify the type but no variable:
catch (Exception)
{
...
}
Personally I'd be very wary of catching an exception without even logging it. It may be required if you're calling a boneheaded API, but it's generally best avoided.
I think they are the same. But the second case raised a compiler warning because you declare an exception you didn't use. I rather like the first one because you say explicitly that you don't use the exception. There is also a third one
catch (Exception)
{
//do something
}
if you want to specify the type of exception but doesn't care about the exception itself.
Generally you should catch specific errors first.
But if you go for catching a general Exception like you do I'd say use the second case:
catch (Exception ex)
{
MessageBox.Show("Error.");
//we never use ex, so is it better to use catch without arguments?
}
this can help you with debbuging since the variable contains the stack trace, exception message...etc. Which you can use for logging the error or something that will help you preventing it.
Be very carefull using this approach, though:
MessageBox.Show("Error.");
Not keeping track of your errors somewhere(like a log file) can cause a really big mess.
In your second example you can reference exception data, like the stack trace, source, etc. It also gives a general message that is sometimes helpful. It tells you WHY you suffered an exception which is important when debugging.
Some exception can not be catch(Exception) catched.
Below excecption in mono on linux, should catch without parameter.
Otherwise runtime will ignore catch(Exception) statment.
System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.
If you encounter the problem like that, try remove parameter of catch statement, log the context vars to find out error cause.
P.S. I don't know how on windows, the program run in windows is normal.
All the time, to avoid any run time error, I use the Exception handler:
as the following:
try
{
//My code which may raise an error.
}
catch (Exception ee)
{
string message = ee.Message;
ShowMessage();
}
My question is:
Is this considered as a good practice or bad practice? (I use the same
lines all the time)
What about the performance issue every time declaring a string?
When using those lines with a method which return a value, the
returning must be after the catch?
That's bad code. Actually very bad.
As all you do with the error message is to assign it to a string that you never use, you are effectively just catching the exception and ignoring it. This is pretty much the worst thing that you can do with an exception, as the program will continue on as if nothing happened, likely with unusable or corrupted data.
When catching exceptions:
Use a more specific Exception type, for example SqlException or IOException, so that you only capture the exceptions that you intend to catch, and that you know how to handle.
When catching an exception, either really handle it, or rethrow it so that it can be handled at a different level.
You should handle known issues first to improve performance, such as null references, empty strings, etc.
Use exceptions for exceptional cases.
Declaring the string isn't a bad thing in there, but its not doing anything other than holding another reference.
You can safely return from a try block. But as Damokles states, you should also have another return else where.
The general structure of exception handling is the following:
try
{
//do struff here
}
catch (...)
{
//handle exception here
}
finally
{
//clean up here
}
There are a couple of things to note in your code that are not entirely right (they are terrible in fact :p):
Only catch exceptions you are ready to handle and do not handle those you are not. This means that you should only catch particular exceptions (FileNotFoundException, ArgumentOutOfRangeException, whatever) that you know can happen in exceptional cases (never use exception handling as a normal execution flow tool). Catching System.Exception is considered bad practice (unless it is for logging purposes and you throw; immeadiately afterwards) because this exception can be thrown by any darn thing, which with all probability you have not foreseen when writing your code and therefore have no clue on how to handle it correctly.
Depending on your situation you should consider using finally blocks in order to clean up whatever you can before exiting the method (be it because of normal execution flow, or an unhandled exception). Note that finally blocks will be (normally) always executed before exiting the method scope.
Do not swallow exceptions and the information they contain. You should consider logging it somewhere (myApplication.log file) and show the user a more friendly "we have aproblem" message. Otherwise the only information you will have when bugs crop up in production will be whatever you show the user. All the valuable information stored in the caught exception will be lost.
There is no need to add exception handler in all the functions. Add the exception handling at the main() which wraps all the functions. Only add exceptions handlers at place where you intend to do some specific exception handling operation to prevent the application from crash.
Return value can be added in the try block.
I assume you are doing this to IGNORE exceptions? In that case you can do it like this:
try
{
// code
}
catch {}
This will catch all exceptions and do nothing with them(ignore).
I would however not recommend doing that, because you will now never know why some functionality in your system is not working as expected because no errors are thrown. I would then recommend at the minimum at least LOG the exception so that you can troubleshoot problems later. A better approach would be to log the exception and re-throw it and then have friendly exception handling at the UI layer.
This is considered a bad practice as you basically ignore the exception. You don't even show it to the user!
It's even double bad, because it is also a bad practice to copy-paste the same lines all over your code.
Recommended usage is to either handle the exception, or do not touch it at all. As it's rather uncommon that the code knows how to handle an exception, the common case is to not catch it at all!
Of course, way up in your main loop, you'll have a try-catch, which will log the exception and/or report the exception to the user.
With respect to your second question: Yes, a return statement can be part of the catch block. But if you don't know what to return, you should not catch the exception!
You should only catch exceptions that you are expecting and know how to handle them. by catch (Exception) you are catching all kind of exceptions in a method is not a good practice.
You can catch all exceptions to just log them or restart you application on fail..
For example
try
{
//My code which may raise an error.
}
catch (FileNotFoundException)//you are expecting this exception
{
//handle file not found here.
}
catch (Exception ee)
{
string message = ee.Message;
Log(message);
throw;//rethrow the exception
}
I've got a new project. Every time you dealing with somebody else code it's an adventure.
Here is what I found:
try
{
.....
}
catch (InvalidOperationException e) {
throw e;
}
catch (Exception e)
{
throw;
}
Anybody has an idea why?
PS
Thanks everybody.
It really helps.
Here are some good sources that you recommended:
Why catch and rethrow an exception in C#?
http://msdn.microsoft.com/en-us/library/0yd65esw.aspx
http://msdn.microsoft.com/en-us/library/ms229005.aspx
Because whoever has written this doesn't have any understanding of how exceptions work in .NET.
If you don't do anything with an exception, don't catch it.
The code you posted would better be written as:
.....
The real danger of this (other than being completely useless...) is that it modifies the call stack. Others have briefly mentioned it in comments, but it deserves to be called out specifically.
When you have throw ex;, the previous call stack is blown away and replaced with the call stack at the point where throw ex; is called. You almost never want to do this. I will often catch an exception, log it, then rethrow the exception. When doing that, you want to just use throw;. This will preserve the original stack trace.
Makes no sense whatsoever to me, but not for the reason you might think.
Catching an exception is not the same thing as handling it. This try/catch block does no handling at all. I think a better, more honest, less verbose solution would have been to remove the try/catch and let the exceptions bubble up to where they can/should be dealt with.
i guess the application wants the outer method calling this to catch the exception instead but this is not the way it should be done, do check these references as they are somewhat similar
Why catch and rethrow an exception in C#?
http://winterdom.com/2002/09/rethrowingexceptionsinc
It is possible that they wanted to implement different handling for InvalidOperationException and other types of exceptions, so they wrote this code as a stub. But then this idea was abandoned so you see this code artifact.
you can improve this code by adding logging.
after every catch, log the information that you throw.
there are some opensource code available for logging.
As all of you probably know, catching and re-throwing a exception in c# this way is evil, because it destroys the stack trace:
try
{
if(dummy)
throw new DummyException();
}
catch (DummyException ex)
{
throw ex;
}
The right way to re-throw an exception without loosing the stack trace is this:
try
{
if(dummy)
throw new DummyException();
}
catch (DummyException ex)
{
throw;
}
The only problem with this is that I get a lot of compilation warnings: "The variable 'ex' is declared but never used". If you have a lot of these, a useful warning may be hidden in the garbage. So, that's what I did:
try
{
if(dummy)
throw new DummyException();
}
catch (DummyException)
{
throw;
}
catch(AnotherException ex)
{
//handle it
}
This seems to work, but I'd like to know if there is any downside of re-throwing an exception that is not set to an variable. How does .net threats this?
Thanks in advance
Edit:
I've changed my code a little bit to make clearer what I wanted to do, as some had misunderstood
I'd like to know if there is any downside of re-throwing an exception that is not set to an variable.
No, there's no downside at all. A variable is only needed if you want to reference the exception in your code, but since you don't need to do that with a throw statement, you don't need a variable at all.
And you have exactly the right idea in attempting to eliminate "noisy" compiler warnings. They have a tendency to bury important errors that you do want to fix, and getting a clean build is always important. The best solution is simply to rewrite the code to use a parameterless catch clause.
However, be aware that in 82% of cases that I see*, it's a mistake to write code that uses throw at all. You generally shouldn't catch exceptions that you don't know how to handle and your only intended "handling" strategy is to rethrow them. There are cases where even using throw can reset the call stack, causing you to lose important debugging information. There are also better alternatives for logging exceptions to catching/rethrowing. You can find more information in the answers to these questions:
Main method code entirely inside try/catch: Is it bad practice?
what can lead throw to reset a callstack (I'm using "throw", not "throw ex")
There's absolutely nothing wrong with letting exceptions bubble up and handling them all in a central place. The rule to keep in mind is that you shouldn't use exceptions for flow control. But there's nothing wrong with throwing an exception in low level code, and showing the user an error message higher up the stack in UI code. Read Microsoft's Best Practices for Handling Exceptions for some general tips.
* Slightly more than the percent of statistics that are made up on the spot.
There is no downside to that. You are simply telling the compiler "I plan to catch this exception but I have no need for a reference to the actual exception", it doesn't affect how things are thrown or how exceptions work. Your latter example is the ideal way to do what you want, however if you are merely going to immediately throw; with nothing else whatsoever in the block, then why catch at all?
If you're not doing anything with DummyException in the catch block (which you can't, since you haven't given it an identifier), why not get rid of the try/catch block entirely? E.g., just do this:
throw new DummyException();
Although at that point, I'd probably evaluate what you're trying to accomplish here and rethink your application architecture so as not to not rely on exception propagation in this manner.
Why catch if your simply going to re-throw? Anyway, you may want to take a look at this previous discussion. Though not identical much of what is discussed is relevant:
Throw VS rethrow : same result?
Actually throwing an exception using "throw;" is a .Net best practice, because it preserves exception stack trace.
Throwing exceptions using "throw ex;" is considered a worst practice, because it looses the original stack trace and should be avoided.
Why catch and rethrow like this? Why do people always have to assume they know every case? Answer: Database transactions.
If you have a better way to do this please speak up Dr. Proton, no offense taken. Keep in mind that there are a lot of different database systems in use but most of them support transaction control (begin/commit/rollback) and have C# interfaces.
pseudocode (a simplified case):
try
{
db.beginTrans();
db.doStuff();
db.doOtherStuff();
db.commitTrans();
}
catch
{
db.rollbackTrans();
throw;
}
Now, it is quite annoying to lose the detail of whether doStuff() or doOtherStuff() failed and I don't see any good reason why C# would toss the line number information in this case. But it seems to. Hence the googling and my subsequent arrival. If I am missing something please do tell.