How Can I Force Execution to the Catch Block? - c#

I am wondering can try..catch force execution to go into the catch and run code in there?
here example code:
try {
if (AnyConditionTrue) {
// run some code
}
else {
// go catch
}
} catch (Exception) {
// run some code here...
}

try{
if (AnyConditionTrue){
//run some code
}
else{
throw new Exception();
}
}
catch(){
//run some code here...
}
But like Yuck has stated, I wouldn't recommend this. You should take a step back at your design and what you're looking to accomplish. There's a better way to do it (i.e. with normal conditional flow, instead of exception handling).

Rather than throwing an Exception in the else, I would recommend extracting the code from your catch into a method and call that from your else
try
{
if (AnyConditionTrue)
{
MethodWhenTrue();
}
else
{
HandleError();
}
}
catch(Exception ex)
{
HandleError();
}

Yes, you have to throw exception :
try
{
throw new Exception("hello");
}
catch (Exception)
{
//run some code here...
}

An effective way to throw an Exception and also jump to Catch as so:
try
{
throw new Exception("Exception Message");
}
catch (Exception e)
{
// after the throw, you will land here
}

if(conditiontrue)
{
}
else{
throw new Exception();
}

Yes, if you throw the exception that you intend to catch from within the try, it will be caught in the catch section.
I have to ask you why you would want to do this though? Exception handling is not meant to be a substitute for control flow.

I think what you want is a finally block: http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx
see this
try
{
doSomething();
}
catch
{
catchSomething();
throw an error
}
finally
{
alwaysDoThis();
}
This is different if/when you do this:
try
{
doSomething();
}
catch
{
catchSomething();
throw an error
}
alwaysDoThis();// will not run on error (in the catch) condition
the the this last instance, if an error occurs, the catch will execute but NOT the alwaysDoThis();. Of course you can still have multiple catch as always.

As cadrel said, but pass through an Exception to provide more feedback, which will be shown in the innerException:
try
{
if (AnyConditionTrue)
{
MethodWhenTrue();
}
else
{
HandleError(new Exception("AnyCondition is not true"));
}
}
catch (Exception ex)
{
HandleError(ex);
}
...
private void HandleError(Exception ex) {
throw new ApplicationException("Failure!", ex);
}

public class CustomException: Exception
{
public CustomException(string message)
: base(message) { }
}
//
if(something == anything)
{
throw new CustomException(" custom text message");
}
you can try this

You could throw an exception to force a catch
throw new Exception(...);

why are you catching an exception? Why not just run the code in your "else" block? If you MUST do it that way, just throw a new exception
throw new Exception();

Slight resurrection, but I wanted to add both a sample (primarily like others) and a use case.
public int GetValueNum(string name)
{
int _ret = 0;
try
{
Control c = (extendedControls.Single(s => s.ValueName == name) as Control);
if (c.GetType() == typeof(ExtendedNumericUpDown))
_ret = (int)((ExtendedNumericUpDown)c).Value;
else
throw new Exception();
}
catch
{
throw new InvalidCastException(String.Format("Invalid cast fetching .Value value for {0}.\nExtendedControllerListener.GetValueNum()", name));
}
return _ret;
}
In my case, I have custom controls - a handful of controls that use a base Windows.Forms control, but add two bools and a string for tracking, and also automatically get registered to a Singleton List<T> so they can be properly fetched without drilling down through control containers (it's a tabbed form).
In this case, I'm creating some methods to easily get values (.Value, .Text, .Checked, .Enabled) by a name string. In the case of .Value, not all Control objects have it. If the extended control is not of type ExtendedNumericUpDown, it IS an InvalidCastException as the method should not be called against that type of control. This isn't flow, but the prescribed usage of invalid cast. Since Control doesn't naturally have a .Value property, Visual Studio won't let me just force an attempt and fail after.

Related

How to resume second method after first method throws an exception C#

While looking on C# try catch tutorial, I got following question. My sample code as follows,
Inside mainMethod() , I need to call three separate methods. Inside testMethodOne(), I need to handle exception as. If testMethodOne() throws exception, without executing testMethodTwo(dt), mainMethod() throwing exception. I need to call testMethodTwo(dt); and testMethodThreee(dt); if testMethodOne() throws exception, how can I do it.
public void MainMethod(data dt){
try{
testMethodOne(dt);
testMethodTwo(dt);
testMethodThreee(dt);
}catch(Exception ex){
throw ex;
}
}
public void testMethodOne(dt){
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
}
I understood your question as follows (but I might be wrong, your questions is not very clear):
Even if one of your testMethods throws an exception, you still want to continue in the normal program flow with the other methods. If at least one of the method failed, mainMethod could then report this as AggregateException.
public void MainMethod(data dt)
{
var exceptions = new List<Exception>();
try
{
testMethodOne(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodTwo(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodThreee(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
It seems as if you want exceptions to alter the flow of your main method without breaking everything. One easy method is to make each 'testmethod' return a boolean.
public bool testMethodOne(dt){
try
{
// Block of code to try
return true;
}
catch (Exception e)
{
// Block of code to handle errors
return false;
}
}
Then in your main code you can go
if(!testMethodOne(dt))
if(!testMethodTwo(dt))
if(!testMethodThree(dt))
//log that all methods failed
The above snippet would try each method until it finds one that succeeds. If that's not the behaviour you are looking for can you reword your question to make it clearer? If you want the opposite to happen just get rid of the ! and it will go until one fails. Alternatively you could put a throw in your catch statement in each of the testMethods, and that would stop execution once one is reached as well.

Object not set to a reference

This issue drives me insane, as I can't see what's causing it. The behavior is unexpected and I just can't see how it can occur. When I execute my plugin using the code below, I get the error message "bada boom". Just as expected.
public void Execute(IPluginExecutionContext context)
{
throw new Exception("bada boom");
try
{
throw new Exception("bada bing");
...
} catch (Exception) { }
...
}
However, when I comment out the first throw, I don't get to see "bada bing". Instead, I get "object not set to a reference"! What the duck?! (Typo intended.)
public void Execute(IPluginExecutionContext context)
{
//throw new Exception("bada boom");
try
{
throw new Exception("bada bing");
...
} catch (Exception) { }
...
}
Here's graphics for the issue.
In your first example the exception is handled at the caller level and up till a catch block is found. In the second example the exception is handled in the mandatory catch or finally block associated with the try of the Execute method.
So in the code inside that catch or finally block you have a null reference exception
void Main()
{
try
{
Execute();
}
catch(Exception x)
{
Console.WriteLine("In main: " + x.Message);
}
}
public void Execute()
{
// Goes to the catch block in main
//throw new Exception("bada boom");
try
{
// Goes to the catch block associated with this try
throw new Exception("bada bing");
}
catch(Exception x)
{
// Uncomment this to see the null reference exception in main
// Console.WriteLine("In Execute: " + x.InnerException.Message);
Console.WriteLine("In Execute:" + x.Message);
}
}
Well, of course, when I say mandatory I want to say that you cant write
try
{
....
}
without a catch or a finally clause following the try. And you can write a catch or finally block without code, but you can't omit one of the two keywords and its block

Catch InvalidOperationException with empty structure

I am trying to catch the InvalidOperationException that can sometimes occur when declaring variables. The following code doesn't work however. Probably because I don't really know how you catch an exception.
public override void Download()
{
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException exception)
{
return;
}
catch (Exception exception)
{
throw;
}
}
}
Any help at all would be very appreciated.
You don't need to throw the exception yourself. Just have:
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
}
catch (InvalidOperationException exception)
{
// Error logging, post processing etc.
return;
}
You shouldn't really be catching the general exception either unless you have a really good reason to - i.e. your application cannot crash, but if you do you need to be able to recover from it.

Throwing (and catching) exception in anonymous method

I have following problem. I want to catch exception as shown below, instead I get NullReferenceException. Is there a way to catch the exception thrown inside of this Anonymous method ?
SynchronizationContext _debug_curr_ui = SynchronizationContext.Current;
_debug_curr_ui.Send(new SendOrPostCallback(delegate(object state) {
throw new Exception("RESONANCE CASCADE: GG-3883 hazardous material failure");
}),null);
I would appreciate any help.
You could still use try/catch inside your anonymous method:
_debug_curr_ui.Send(new SendOrPostCallback(delegate(object state) {
try
{
throw new Exception("RESONANCE CASCADE: GG-3883 hazardous material failure");
}
catch (Exception ex)
{
// TODO: do something useful with the exception
}
}), null);
As an alternative you could modify this Send method and catch the exception just before invoking the delegate:
public void Send(SendOrPostCallback del)
{
// ...
try
{
del();
}
catch (Exception ex)
{
// TODO: do something useful with the exception
}
// ...
}
I suspect that you are getting the NullReferenceException because _debug_curr_ui is null.
Otherwise you should be able to wrap the code that you posted in a try/catch block and catch the excpetion. You should also think about using ApplicationException and not Exception.
try
{
Action someMethod = delegate() { throw new ApplicationException("RESONANCE CASCADE: GG-3883 hazardous material failure"); };
someMethod();
}
catch
{
Console.WriteLine("ex caught");
}
MSDN ApplicationException
If I understand correctly, you want the anonymous delegate to throw the exception, and you want to catch this exception somewhere outside of the anonymous delegate.
In order to answer that, we will need to know what you are actually doing with the delegate, and how it is being invoked. Or, to be more specific, what does the _debug_curr_ui.Send method do with the delegate?
something like below
delegate(object obj)
{
try
{
}
catch(Exception ex)
{
}
}

Exception handling problem

I'm trying to write some code that catches a particular exception and throw a more useful one for something higher up the call stack to deal with but also catch more general exceptions and handle them.
The code is something like this:
try
{
// Do stuff
}
catch (SomeException e)
{
throw new SomeExceptionWithContextInfo();
}
catch (Exception e)
{
// Handle unexpected exception gracefully
}
The problem I'm having is that the general exception is catching my new exception. is there a way to avoid this?
My current solution involves checking the type of the exception and throwing it again if it's type is what I just created.
The code you've posted should work, as shown in this test app:
using System;
class OtherException : Exception {}
class Test
{
static void Main(string[] args)
{
try
{
Foo();
}
catch (OtherException)
{
Console.WriteLine("Caught OtherException");
}
}
static void Foo()
{
try
{
string x = null;
int y = x.Length;
}
catch (NullReferenceException)
{
throw new OtherException();
}
catch (Exception)
{
Console.WriteLine("Caught plain Exception");
}
}
}
This just prints "Caught OtherException" not "Caught plain Exception". Are you sure you don't have a nested try block in your real code? Could you post a short but complete example which shows your problem?
Do you really need to catch Exception in your method though? That's very rarely a good idea.
You're doing it right. The general exception will not catch the specific one.
The code you posted is the way to do it (catch for more specific exception must appear first).
I suggest looking again at the code, as either they are not in that order, or the code isn't actually throwing that exception type.
Here is a link on msdn about try-catch: http://msdn.microsoft.com/en-us/library/0yd65esw(VS.80).aspx
Don't catch general exceptions might be the answer? Find out which Exceptions that can be thrown and catch them separately.
try { // Outer try/catch
DoSomething();
try {
/* */
} catch(NotGeneralException e) {
/* */
} catch(AnotherNotGeneralException e) {
throw new SomeOtherException("Exception message");
}
} catch(SomeOtherException e) {
/* */
}
Alternatively only catch a general exception and rethrow SomeOtherExcepion
try {
} catch(Exception e) {
throw new SomeOtherException("Exception message");
}

Categories