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);
}
Related
This question already has answers here:
Why is TargetInvocationException treated as uncaught by the IDE?
(2 answers)
Closed 8 years ago.
When using property reflection to SetValue, the property throws a TargetInvocationException. However, since the call to SetValue is an invocation, the exception is caught and not handled in the property. Is there way to handle the Target Exception in the property and have it ONLY thrown in the main program?
I want this throw to be as if I just made a method call, not an invocation.
Edit for clarification:
The problem I am having is that within the reflect class, I am getting a debug message that says "Exception was unhandled by user code". I have to 'continue' with the debug session and the inner exception is the 'real' exception. Is this just to be expected? I dont want to get warned (and I dont want to hide warnings), I want the code to fix the warning.
public class reflect
{
private int _i;
public int i
{
get { return _i; }
set
{
try{throw new Exception("THROWN");}
catch (Exception ex)
{ // Caught here ex.Message is "THROWN"
throw ex; // Unhandled exception error DONT WANT THIS
}
}
}
}
class Program
{
static void Main(string[] args)
{
reflect r = new reflect();
try
{
r.GetType().GetProperty("i").SetValue(r, 3, null);
}
catch(Exception ex)
{ // Caught here, Message "Exception has been thrown by the target of an invocation"
// InnerMessage "THROWN"
// WANT THIS Exception, but I want the Message to be "THROWN"
}
}
}
You need the InnerException:
catch(Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
This isn't specific to reflection - it's the general pattern for any exception which was caused by another. (TypeInitializationException for example.)
Sorry, can't comment yet. Two things:
1) why are you first catching ex in your reflection class and then throwing it again? This shouldn't be the problem, though.
2) I think you are getting your exception. Check the "Exception has been thrown"'s inner exception.
What happens here ?
I wonder whether SaveError() can be called after exception block ?
Does the Main.cs get noticed about caught error?
I want to see the story behind this case.
What is the value of the variable "a" ?
note: Asume there has been an error in try block.
Main.Cs
public void RunAll()
{
....
int a = doSubTask();
}
A.cs
public int doSubTask(){
try{
..
..
return 1;
}catch(Exception Ex)
{
throw new AppException("Error", ex);
}
finally
{
SaveError();
return -1;
}
return 0;
}
The return 0; after the finally is redundant since finally will be called always even if there was an exception inside the cache or not.
Anyway, leaving the finally block with return will cause you a compilation error which means in your case, since you are throwing an exception from inside the catch block, a will not be set by any value.
First of all, you can't return value within finally block, C# does not allow this.
finally always executes even if there are errors (i.e. control goes in catch block). So in your case, the return value will always be -1, it does not matter whether exception was thrown or not.
The last statement return 0; is non-reachable.
I guess you can modify your code like this. You shouldn't use more than one "return" key in a method.
public int doSubTask()
{
int retval = 0;
try
{
//to do
retval = 1;
}
catch (Exception Ex)
{
SaveError();
retval = -1;
throw new AppException("Error", ex);
}
finally
{
// do something even there is error or not
}
return retval;
}
Short answer: it depends from you machine ^^
As you can see in this MSDN article: http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx ,
if the exception is unhandled it's up to your system to decide if the Finally statement is executed or not.
Also: you can't return a value in a finally statement.
The whole method Foo seems a bit confusing to me.
If your goal is to try a "risky" operation and handle the error you shouldn't rethrow the exception without having the outer code handle that.
So, if you want the RunAll method to know if there's been an error, you should set it's code inside a try-catch statement and rethrow the exception in the Foo method, without the finally statement so the rethrown exception "bubbles up" the chain and gets handled in the calling method :)
It is not allowed to try to "leave" a finally block, so it will not be valid to say return -1; inside the finally block. So your code will never compile.
error CS0157: Control cannot leave the body of a finally clause
Hence, there exists no question "what will happen when it runs".
I'm having an issue with a try/catch block, but I can't seem to find out exactly how try/catch works when it's running that I think might have my answer. I have the following try/catch block:
try
{
...
}
catch (MyException e)
{
Log.Error("oh no!");
throw;
}
Now when I run this code I'm getting a System.TypeLoadException: Could not load type SDK.MyException from assembly "SDKSampleLibrary, Version... etc error.
I'm wondering 2 things. First, when does the computer check to see if MyException is there. Is it when it gets to the try or when it gets to the catch? Second, the SDKSampleLibrary.dll is there. How do I tell why it's not seeing it?
If the class MyException gets thrown within the try area, it will get handled inside the catch, See my example below where i throw a new exception which would get handled by the catch statement. However any other kinds of exceptions would not be handled/
try
{
throw(new MyException()); // handled by the catch
throw(new ParseException()); //not handled.
int test = "test" //not handled
}
catch (MyException e)
{
Log.Error("oh no!");
throw;
}
can also catch general exceptions to catch ALL exceptions like:
try
{
throw(new MyException()); // handled by the catch
throw(new ParseException()); //handled.
int test = "test" //handled
}
catch (Exception e)
{
Log.Error("oh no!");
throw;
}
The compiler sees the class since it is blue and does not give compile errors. The problems is happening when you are running the code. I think the problem is in de code that throws the exception which cannot create it. You could try to use the normal Exception type in the catch block and then set a break point.
The problem is not with the try/catch block but rather the problem is the type of exception that you are trying to catch as specified by the exception that your code is throwing. This exception occurs when the runtime tries to load the MyException object. You should make sure that the MyException inherits either from the Exception base class or from any of its children.
catch (OracleException e)
{
Cursor.Current = Cursors.Default;
_instance = null;
if (e.ErrorCode == -2147483648) // {"ORA-01017: invalid username/password; logon denied"}
{
throw new Exception("Nepravilno ime uporabnika ali geslo");
}
else
{
throw new Exception("Ne morem se povezati na podatkovno bazo. Preveri povezavo!");
}
}
but i always get Unhandled exception. Why?
At the risk of stating the obvious... Because you're not catching the Exception you throw in your catch block? Or, perhaps, something else is being thrown in the try block that isn't an OracleException.
What are you expecting to happen?
Just to be totally clear (to make sure that we're on the same page), an exception that's thrown but never caught will result in an unhandled exception (by definition). Throwing an exception from within a catch block is identical to throwing it from anywhere else; there still needs to be a try-catch somewhere to catch it. For example, this exception will be caught:
try {
throw new Exception("Out of cheese error"); // Caught below
}
catch (Exception) { }
But this one results in a new exception being propogated:
try {
throw new Exception("Out of cheese error"); // Caught below
}
catch (Exception) {
throw new Exception("418: I'm a teapot"); // Never caught
}
And this code catches both exceptions:
try {
try {
throw new Exception("Out of cheese error"); // Caught in inner catch
}
catch (Exception) {
throw new Exception("418: I'm a teapot"); // Caught in outer catch
}
}
catch (Exception e) {
Console.WriteLine(e.Message); // "418: I'm a teapot"
}
Your code does not in anyway swallow an exception. All it does is catch one type of exception and throw another type of exception. If you have an unhandled exception before you write this code, you will still have one after you write it.
--UPDATE --
Referring to your comment to another answer, if you want to display a message and stop executing code then try:-
catch (OracleException e)
{
Cursor.Current = Cursors.Default;
_instance = null;
if (e.ErrorCode == -2147483648) // {"ORA-01017: invalid username/password; logon denied"}
{
MessageBox.Show("Nepravilno ime uporabnika ali geslo");
}
else
{
MessageBox.Show("Ne morem se povezati na podatkovno bazo. Preveri povezavo!");
}
// this exits the program - you can also take other appropriate action here
Environment.FailFast("Exiting because of blah blah blah");
}
I assume you call hierarchy look like this:
Main
|-YourMethod
try {}
catch (OracleException) {throw new Exception("blah blah")}
So you see, the OracleException which occured in YourMethod is being caught by catch block, but then you throw a new one which goes into Main, where nothing handles it. So you should add an exception handler on the previous level.
Also, do not hide the original OracleException, throw your exception this way throw new Exception("your message", e). This will preserve the call stack.
Because you're only handling the OracleException. Nothing is handling the Exception() you are throwing.
You're catching the OracleException which means you're prepared to handle it - what does handling it mean to you? Logging it and moving on? Setting some state and moving on? Surely, you don't want to pop up gui in a data access component right? If you're not prepared to handle it, let it bubble up and handle it at an outer layer.
You also shouldn't throw exceptions of type Exception. Create your own strongly typed exceptions so they can be handled, or, simply log and call throw; which rethrows the original.
If you throw a new type of exception ensure you're passing the original exception as the inner exception to ensure you're not hiding details.
I did a write up on some best practices with C# exceptions:
Trying to understand exceptions in C#
Hope that helps
Is it possible to call catch for a special condition when you are inside of try without using system error? For instance if a value int value 1 and then I want to use "catch".
One of the biggest sins in programming:) Don't use exceptions for managing programming flow! Now to your question - the catch block can be called in case an exception is thrown.
Your wording is a bit confusing but I think this is what you want.
int value = GetValue();
try
{
if (value == 1)
throw new InvalidOperationException();
HappyPath(value);
}
catch (InvalidOperationException)
{
SadPath(value);
}
Incidentally using exceptions for control flow is not the best practice.
No. You should catch exceptions (you can filter them by type), and then inside catch block you can filter on any condition.
It is not possible in C# to throw an exception that doesn’t derive from Exception, even though the CLR allows it.
It is possible to catch such an exception, but it is not possible to access the object that was thrown:
try
{
MethodThatThrows();
}
catch // This catches everything, even objects not deriving from Exception
{
// Process exception
}
As soon as you specify a variable (e.g. catch (Exception e)), C# requires that the type is Exception or derived from it.
I think you might be saying that you want to catch an exception only in specific circumstances, and pass it through in all other circumstances? In that case, you can just use an if to check for the condition and then throw to re-throw the exception:
try
{
// ...
}
catch (Exception e)
{
// If it’s any value other than 1, we’re not interested in the exception
if (value != 1)
throw; // note: throw; *not* throw e;
// Process the exception here
}