try
{
//This code BlockLine no 1Line no 2Line no 3etc
}
catch (Exception ex)
{
LblError.Text= ex.Message + ex.InnerException.Message
}
I have a code with a try catch block. The try block has more than one line of code. I would like to know which line present within the try block is raising the exception.
You will need to look at the Stack Trace of the exception to track the line that throws the exception.
however if you want to get the full details about the exception use ToString method
( using System.Diagnostics; )
int lineNumber = (new StackTrace(ex, true)).GetFrame(0).GetFileLineNumber();
var fileName = (new StackTrace(ex, true)).GetFrame(0).GetFileName();
Should give you where the problem started.
Related
I am trying to learn how to debug and handle errors in C# code using VS2012 for Desktop. I am stepping-through the below code using the Step Into F11 technique.
I understand how the execution of code jumps between different parts of code. I have messages printed out to console to help me identify which step is being executed. I have split my screen so I can see which line of code I'm stepping into and the output messages in the console at the same time.
On line 70 (marked in the comments) - when the nested index is passed to the throwException() I do not understand why there is a throw keyword and what its functionality is. Why does the pointer jump to the nested finally block but then it goes back all the way to the main and throws IndexOutOfBounds exception. What does that mean? I see where the execution jump in the code but I don't understand why it just says throw. Does it mean that the exception is already handled? But how?
I read that when you throw an exception there is no need to add a break; statement because the switch statement breaks when it meets throw keyword, but I am not sure this is the right path of thinking in this example.
Please, help me understand the meaning of the throw keyword on line 70.
Thank you in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch07Ex02
{
class Program
{
static string[] eTypes = { "none", "simple", "index", "nested index" };
static void Main(string[] args)
{
foreach (string eType in eTypes)
{
try
{
Console.WriteLine("Main() try block reached."); // Line 19
Console.WriteLine("ThrowException(\"{0}\") called.", eType);
ThrowException(eType);
Console.WriteLine("Main() try block continues."); // Line 22
}
catch (System.IndexOutOfRangeException e) // Line 24
{
Console.WriteLine("Main() System.IndexOutOfRangeException catch"
+ " block reached. Message:\n\"{0}\"",
e.Message);
}
catch // Line 30
{
Console.WriteLine("Main() general catch block reached.");
}
finally
{
Console.WriteLine("Main() finally block reached.");
}
Console.WriteLine();
}
Console.ReadKey();
}
static void ThrowException(string exceptionType)
{
Console.WriteLine("ThrowException(\"{0}\") reached.", exceptionType);
switch (exceptionType)
{
case "none":
Console.WriteLine("Not throwing an exception.");
break; // Line 50
case "simple":
Console.WriteLine("Throwing System.Exception.");
throw new System.Exception(); // Line 53
case "index":
Console.WriteLine("Throwing System.IndexOutOfRangeException.");
eTypes[4] = "error"; // Line 56
break;
case "nested index":
try // Line 59
{
Console.WriteLine("ThrowException(\"nested index\") " +
"try block reached.");
Console.WriteLine("ThrowException(\"index\") called.");
ThrowException("index"); // Line 64
}
catch // Line 66
{
Console.WriteLine("ThrowException(\"nested index\") general"
+ " catch block reached.");
throw; // Line 70
}
finally
{
Console.WriteLine("ThrowException(\"nested index\") finally"
+ " block reached.");
}
break;
}
}
}
}
The above code compiles and runs with no errors.
Keyword throw can be used all by itself inside a catch clause to rethrow whatever exception has been caught by that catch block. It lets you "plug in" some execution logic in the process of handling the exception without disrupting the details of where the exception has been thrown.
In this case, you are able to log the details to console, and then re-throw the exception as if you never handled it. Note that this is different from catching an exception and wrapping it in your own, because the details of the original exception are preserved.
throw; inside a catch says "I don't actually know what to do about this exception so let somebody else higher up the stack catch it (without me having modified it)."
The throw in question will re-throw the exception, such that the stack trace and other info is preserved.
Have a look at Rethrow to preserve stack details
Also from try-catch (C# Reference)
If you want to re-throw the exception currently handled by a
parameter-less catch clause, use the throw statement without arguments
catch
{
throw;
}
The throw keyword is used to re-throw caught exceptions without losing the correct stack trace. It is used to do some execution when the exception is caught (for example logging, as it is in your example).
Please see this: SO qeustion on rethrowing exceptions
and this: codinghorror blogpost (please note the clarifications in the comments)
I`m writing class. Here is one of functions:
public string GetAttribute(string attrName)
{
try
{
return _config.AppSettings.Settings[attrName].Value;
} catch(Exception e)
{
throw new ArgumentException("Element not exists", attrName);
return null;
}
}
Then, I am using it in the main form MessageBox.Show(manager.GetAttribute("not_existing_element"));
Visual Studio throws an Exception at line:throw new ArgumentException("Element not exists", attrName);
but, I am want to get an Exception at line MessageBox.Show(manager.GetAttribute("not_existing_element"));
How can I do that?
P.S: Sorry for bad English.
You are misusing exception handling. In your code, if you get (for example) a NullReferenceException, you will catch it and then throw an ArgumentException.
Rewrite your method to not have any exception handling:
public string GetAttribute(string attrName)
{
return _config.AppSettings.Settings[attrName].Value;
}
This way, you are not resetting the stack trace and swallowing the original exception.
In terms of getting an exception on the calling line - you will never be able to get an exception at a line that isn't throwing an exception.
A couple of things:
First, you'll get an unreachable code warning for the return null statement in your catch, because the throw will execute before the return. You can simply delete the return null statement.
Secondly, I'm not sure what you mean by getting the exception at the MessageBox line, but I think you mean you want to catch it there. Wrap the call to MessageBox in a try-catch.
try
{
MessageBox.Show(manager.GetAttribute("not_existing_element"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I am reading a file line by line from text file and do some processing. The problem is that if some error occurs at some line. Then an exception is generated, what I want is that I want to ignore that error and move to the next line to read.
But if an exception is generated then I cant continue reading input lines. Please help.
If I'm assuming what you're asking for correctly, here's a basic outline of what your code could look like:
using (StreamReader reader = File.OpenText("Path\to\your\file"))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
try
{
ProcessLine(line);
}
catch { /* Ignore exceptions */ }
}
}
It's generally not a good idea to blindly catch all exceptions, so if you can, you should filter the exceptions caught by your catch block to something more specific.
See exception handling. http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.71).aspx
If you really want to "ignore" exceptions, you can do something like:
try
{
foo(); // Something that may throw an exception
}
catch
{
}
See http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx for more info.
But usually, an exception means something bad happened, and you'll probably want to handle that somehow.
try
{
//put the statement throwing the exception here
}
catch
{
//will eat the exception
}
//execution will continue here
Difficult to understand what you want to achieve, but you probably are asking for something like this:
while(condition)
{
try {
//process file line here
}
catch (Exception ex) {
LogException(ex);
}
}
Not a good design decision in my opinion, by the way. Avoid it if you can.
Use a try catch and log the error. Your code would look like this:
try
{
//read lines here
}
catch(Exception ex)
{
//log the exception but don't throw anything.
}
You may be tempted to do nothing in the catch, but you will likely regret it later.
Try catch article:
http://www.homeandlearn.co.uk/csharp/csharp_s5p6.html
You simply need to wrap your processing code in a try / catch block.
try
{
DoSomeProcessing(lineThatIreadFromFile);
}
catch
{
// Log or Ignore error here
}
However, please note that typically, just swallowing exceptions is never a good idea. You should either fail your program (if unrecoverable), or potentially log those somewhere so you can fix why your program is failing.
Based on the very limited information you provide there are two things you can do:
Enclose the offending line with an empty catch block. Wait for next maintainer to do bad things to you.
Understand why the exception is happening and modify the code such that the next maintainer understands why it is safe that you ignored a certain condition
This is not a good approach. You should be proactive and catch specific exceptions you can recover from. Catch them as close to the place where they are thrown from. And let the rest of them bubble up and terminate the process. By swallowing all exceptions you will get an illusion of robustness while in fact your code may be full of bugs. There is simply no 'quick and dirty' approach to exception handling. See this answer.
Avoid handling errors by catching non-specific exceptions, such as
System.Exception, System.SystemException, and so on, in application
code. There are cases when handling errors in applications is
acceptable, but such cases are rare.
An application should not handle exceptions that can result in an
unexpected or exploitable state. If you cannot predict all possible
causes of an exception and ensure that malicious code cannot exploit
the resulting application state, you should allow the application to
terminate instead of handling the exception.
You need:
using System.IO;
to get this to work.
You can try:
try
{
string path = ""; // You must add the path here. Else it won't work.
string[] lines = File.ReadAllLines(path);
foreach(string line in lines)
{
Console.WriteLine(line);
}
} catch (Exception ex, IOException ioex) {
// It's optional. You can remove "Exception ex, IOException ioex" if you want. You can delete the code below too.
Console.WriteLine(ex.ToString());
Console.WriteLine();
Console.WriteLine(ioex.ToString());
} finally
{
// in this "finally" section, you can place anything else. "finally" section isn't important, just shows that method has no exceptions.
// you can add something else like: Console.WriteLine("Code has no exceptions. Great!");
}
Good for advanced notepads.
EDIT: If you don't like the previous solution, this one can help you.
string path = ""; // Again, path.
string[] lines = File.ReadAllLines(path);
foreach(string line in lines)
{
try
{
Console.WriteLine(line);
} catch(Exception ex, IOException ioex)
{ /* exception */ }
}
----- or -----
string path = Console.ReadLine();
int turns = 0;
int maxturns = (File.ReadAllLines(path)).Count();
while (turns < maxturns)
{
try
{
Console.WriteLine(File.ReadLines(path).Skip(turns).Take(1).First());
} catch (Exception ex, IOException ioex) { /* exception */ }
turns++;
}
try
{
try
{
throw new Exception("From Try");
}
catch
{
throw new Exception("From Catch");
}
finally
{
throw new Exception("From Finally");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
The above code's output is: From Finally.
Why it's not From Catch?
-or-
How can i catch & log from outside both exceptions?
Because the finally block executes after the catch block, overriding the exception.
And when an exception happens during the handling of an earlier one, the first one is lost.
How can i catch & log from outside both exceptions?
By not throwing inside a finally block. That is always a bad idea.
If you want to log in an inner catch block use throw; or pass the first exception as InnerException of the new one. That is why InnerException exists.
This is the behaviour as it is defined by the C# language specification. Handling of the exception thrown inside the try block is aborted and instead the exception thrown in the finally block will be handled.
The relevant section 8.9.5 The throw statement explains how exceptions are propagates:
In the current function member, each try statement that encloses the throw point is examined. For each statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:
If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (ยง8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.
Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.
Add an extra layer of try-catch blocks like the following:
try {
Exception fromCatch = null;
try {
throw new Exception("From Try");
}
catch {
try {
throw new Exception("From Catch");
}
catch (Exception e) {
// catch failed -> store exception
fromCatch = e;
}
}
finally {
try {
throw new Exception("From Finally");
}
catch (Exception e) {
// i can think of better exception merging... but this shows the idea
throw new Exception(e.Message, fromCatch);
}
// throw fromCatch, in case "From Finally did not happen"
throw fromCatch;
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
if (ex.InnerException != null) {
Console.WriteLine(ex.InnerException.Message);
}
}
Reports:
From Finally
From Catch
Edit: this is obviously the answer for question two, as the "why" is answered sufficiently :)
finally always runs; and it always runs last. So the lat thing done by the inner try was the finally and that threw something that was caught by the outer catch
not sure if i understand part2 of the question
finally happens no matter what. Regardless of whether there was an exception in the try or catch. Thus, you see "From Finally". (This actually is the entire purpose of the finally clause. So you can put code in there that will clean up resources and the like no matter what -- even if there's an exception.)
Your code throws a new Exception from each part of the try/catch/finally statement. You are essentially swallowing the previous exception when you create the new error. You can add your "From Try" message to your "From Catch" message with something like
catch(Exception ex)
{
throw new Exception(ex.Message + ":" + "From Catch");
}
I don't know know how you could chain that in the finally though.
This is a very good question, and one that is kind of tricky. Let's go through this step by step:
try
{
throw new Exception("From Try");
}
catch
{
throw new Exception("From Catch");
}
In the code above, Exception("From Try") is thrown and caught by the catch clause (pretty simple so far). The catch clause throws an exception of it's own, which normally we would expect (because the catch is nested in a larger try-catch block) to be caught immediately, but...
finally
{
throw new Exception("From Finally");
}
The finally clause, which is guaranteed to (try to) execute, comes first, and throws an exception of it's own, overwriting the Exception("From Catch") that was thrown earlier.
"A common usage of catch and finally
together is to obtain and use
resources in a try block, deal with
exceptional circumstances in a catch
block, and release the resources in
the finally block" - MSDN Article
Following this train of logic, we should try our best to refrain from writing code in our catch and finally blocks that is exception-prone. If you're worried about situations like the one you presented cropping up, I'd recommend logging the exceptions and their related information out to an external file, which you can reference for debugging.
Because the finally block is always executed.
try
{
try
{
throw new Exception("From Try");
// (1) A new exception object A is created here and thrown.
}
catch // (2) Exception object A is catched.
{
throw new Exception("From Catch");
// (3) A new exception object B is created here and thrown.
}
finally // (4) Execution is forced to continue here!
{
throw new Exception("From Finally");
// (5) A new exception object C is created here and thrown.
}
}
catch (Exception ex) // (6) Exception object C is catched.
{
Console.WriteLine(ex.Message);
}
Every new'd exception object in step (3) and (5) discards the previous one. Since the finally block is always executed all what remains is the exception object C from step (5).
What happens if both catch and finally blocks throw exception?
When the finally block throws an exception, it will effectively hide the exception thrown from the catch block and will be the one ultimately thrown. It is therefore important to either log exceptions when caught, or make sure that the finally block does not itself throw an exception, otherwise you can get exceptions being thrown that are stifled and never seen.
When catch throws an exception, finally block will be run and then exit with an exception.
If the finally block throws an exception, the block will exit with an exception.
The last exception thrown is thrown.
Its already been answered well by adrianbanks, but the following post should be interesting:
Interesting Exception Results: Throwing Exceptions From the Finally Block
HI Nwaman i think you answer is wrong i have tested it in windows appliaction, i found if u write a program like the below one
try
{
string s = "hu";
int i = int.Parse(s);
}
catch (Exception ex)
{
string s = "hu";
int i = int.Parse(s);
throw new Exception();
}
finally
{
MessageBox.Show("hi");
}
and this will not result finally to excute,