Throw exception gives same message all the time - c#

I have a try and catch in my Main.cs
try
{
}
catch(exception e)
{
Console.WriteLine(e.Message)
}
In a other class i have:
if (....)
{
//input
}
else
{
throw new Exception("Custom Error Message1"}
}
In a other class i have a similar situation, but insteed the message is different here.
When a error occurs in the 2nd class the same message from the one above displays, what exactly is the cause of this and what could prove to be a solution?
Thanks in advance.

Have you examined the stack trace? That might tell you something, n'est-ce-pas?

In Visual Studio, go to Debug-Exceptions and set Common Language Runtime exceptions to break when THROWN. Now run your program in debug and you'll see which exception is actually being thrown and can examine the call stack.

Related

Fire or Not Exception on Debug

I have a class Dispatcher with a method Send as follows:
public class Dispatcher : IDispatcher {
public void Send(Order order) {
Type type = typeof(IOrderHandler<>).MakeGenericType(order.GetType());
IOrderHandler handler = (IOrderHandler)ObjectFactory.GetInstance(type);
try {
handler.Handle(order);
} catch (Exception exception) {
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.Send(exception);
}
}
} // Send
I am handling orders and catching exceptions ...
When I am debugging I would like to still fire the exception.
How can I do this?
Thank You,
Miguel
Just add this line to your catch block:
if (System.Diagnostics.Debugger.IsAttached) throw;
You can add the following in your catch block:
#if DEBUG
throw;
#endif
So your code would look like:
try
{
handler.Handle(order);
}
catch (Exception exception)
{
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.Send(exception);
#if DEBUG
throw;
#endif
}
If you want the exception notification in IDE during debugging in Release configuration, then use #Hans Passant's answer, because that will let you know about the exception for both Release and Debug configuration.
Well, based on the fact that you'd like the exception to still be thrown, but only when debugging, you could do this:
Open the Debug menu and choose Exceptions.
When the dialog loads, tick the check box next to Common Language Runtime Exceptions under the Thrown heading.
This will cause you to get a first chance exception. What that means is you'll be notified by the IDE, when debugging, and you'll get a chance to handle it before processing continues. This will actually let you see it before it even gets logged.
What's more, you can actually unselect exceptions you don't want with this approach because they are broken down by exception type underneath the Common Language Runtime Exceptions grouping.
More detail...
Go to Debug > Exception and check the CLR exceptions for "thrown", this will take you right there. alternatively place a breakpoint on the catch block.

How do I find the exception type of an exception that gets thrown in C#?

I am using a library that doesn't seem to document the exceptions. This library is used to communicate with a product the company makes. I want to be able to differentiate between the exceptions that get thrown but I don't know the names of the exceptions (for example between a communication timeout or under-voltage condition).
All of their examples only use catch(Exception ex). How can can I find what I need to use to catch the individual errors? When I do ex.toString() I get something like this:
System.Exception: Timeout
at CMLCOMLib.EcatObj.Initialize()
at copley_cmo_test.MainWindow.btnConnect_Click(Object sender, RoutedEventArgs e)
in c:\Users\adam.siembida\Desktop\copley_cmo_test\copley_cmo_test\MainWindow.xaml.cs:line 41
This:
System.Exception: Timeout
shows that they're just throwing a bare System.Exception, e.g.
if (weHaveNoApiDesignSkills)
{
throw new Exception("Timeout");
}
It's possible that there are some exceptions which are better designed, but the one you've shown isn't promising :(
Unfortunately unless you start using the message in the exception to differentiate between them (which is almost always a bad idea) you're stuck. It may be worth asking the authors of the library to see if they can improve matters for a future release.
Catch it with a catch-all construct such as catch(Exception ex), then examine the Type returned by ex.GetType(). If it's equal to typeof(Exception), it means that they aren't throwing anything more specific than Exception.
By the way, if you're stopped when the exception has been caught (ie, in a catch block), if you enter $exception in the watch window, you will see the entire exception.
When the API in library which you are using is not documented properly , you should catch the base exception and log it not only by the message instead whole exception by converting the exception to string . Eg.
try
{
//api call which throws exception.
}
catch(Exception ex)
{
//log ex.ToString();
}
use a decompiler for example:
http://www.jetbrains.com/decompiler/
in .net there's no explicit exception declaration like in java so as i see it it's the only way.

Exceptions not propagating from a reflected method call in c#

When calling a method via methodInfo.Invoke, if an exception is thrown it does not seem to propagate up to my catch blocks.
object value;
try
{
value = myMethod.Invoke(null, parameters);//program crashes with uncaught exception
}
catch
{
throw new Exception("Caught!");//never executed
}
The particular exception this method is raising is KeyNotFoundException, but that shouldn't matter because I'm catching everything right?
The particular error message I get from Visual Studio is
KeyNotFoundException was unhandled by user code
whereas normally the message would say
KeyNotFoundException was unhandled
if the call was not a reflected invocation.
I could just have the method check to see if they key is in there, and if not return null, but Using exception handling seems preferable. Is there any way to propagate exceptions up from a reflected method call?
This could be an issue with the Visual Studio debugger as well. As noted in the accepted answer to this similar question here, there are a few workarounds that you can do. The simplest of which is changing your Visual Studio debugger to turn off "Just My Code" in Tools -> Options -> Debugging -> General. You can also wrap it in a delegate or explicitly try to catch the invocation exception and inspect the inner exception of that, which should be your KeyNotFoundException.
It works for me:
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var method = typeof(Program).GetMethod("ThrowException");
try
{
method.Invoke(null, null);
}
catch (TargetInvocationException e)
{
Console.WriteLine("Caught exception: {0}", e.InnerException);
}
}
public static void ThrowException()
{
throw new Exception("Bang!");
}
}
Note that you do need to catch TargetInvocationException which is the exception thrown directly by Method.Invoke, wrapping the exception thrown by the method itself.
Can you come up with a similar short but complete program which demonstrates the problem?
If an error occurs during a method invoked with reflection, it should throw a TargetInvocationException that wraps (via .InnerException) the original. There are, however, a few methods that could cause more terminal fails, such as a few methods around winform creation / the message loop.
It is also possible that the method is working, but is causing additional work to happen on another thread, and it is that that is failing. This would kill the thread, and you can't catch it as it isn't on your thread. This would be particularly likely if your code is actually on a worker thread.

Determining which code line threw the exception

In dotNet a line throws an exception and is caught, how can I figure out which line in which file threw the exception? Seems relatively straightforward, but I can't figure it out...
You can only do it if you have debug symbols available.
catch(Exception ex) {
// check the ex.StackTrace property
}
If you want to debug such a situation in VS, you'd better just check Thrown checkbox for Common Language Runtime Exceptions in Exceptions dialog located in Debug menu. The debugger will break as soon as the exception is thrown, even if it's in a try block.
Personally, I just log the exception's ToString() return value. The whole stack trace is included. It's one line of code ... dead simple.
You could use the StackFrame Class:
try
{
...
...
}
catch(...)
{
StackFrame sf = new StackFrame(true);
int lineNumber = sf.GetFileLineNumber();
int colNumber = sf.GetFileColumnNumber();
string fileName = sf.GetFileName();
string methodName = sf.GetMethod().Name;
}
Well, in .NET you have whats called a FirstChanceException. These essentially are thrown before an exception is handled. There are two ways of looking at the issue that you're presenting here. One is from a debugging angle. If debugging you can just set your debugger to catch thrown exceptions from the Debug/Exceptions window. This is easier in an interactive context. IF you need to record this information from within a non-interactive context then I would do something similar to what CMS is talking about...
try
{
...
}
catch(Exception ex)
{
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(ex);
System.Diagnostics.StackFrame firstFrame = stackTrace.GetFrame[0];
Console.WriteLine(firstFrame.GetFileLineNumber);
...
}
The only difference here is that we get the entire Stack Trace, then go to the first frame, which is where the exception was originally thrown.

Thoughts on try-catch blocks

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

Categories

Resources