It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is it possible to add multiple exception in an try block in c# ?
if possible,please provide with sample code
Thanks,
Santhu
you can provide multiple catch block block for a single try block like this:-
try
{
//your code
}
catch(ExceptionClass e)
{
//code to handle exception
}
catch(ExceptionClass2 e)
{
//code to handle exception
}
catch(ExceptionClass3 e)
{
//code to handle exception
}
but you always have to take care of hierarchy of Exception Classes. like for example, ExceptionClass should not be the Super class of ExceptionClass2 and ExceptionClass3.
Remember to use exceptions from specific to more generics in different catch block
try {}
catch(FileNotFoundException fex) {}
catch(IOExceoption iex) {}
catch(Exception ex) {}
finally {}
Yes
try
{
stuff()
}
catch (Exception1 e1)
{
}
catch (Exception2 e2)
{
}
finally
{
}
You mean like this?
try
{
// Your code
}
catch(an exception)
{
}
catch(a different exception)
{
}
catch(any exception you want)
{
}
Related
Probably a stupid question... but here goes anyway...
I would like to know if the quartz.net job will be active to run on the next iteration though there is an exception( which is handled) in the current iteration. Can anyone please explain me if my understanding is correct?
public void Execute(IJobExecutionContext context)
{
_logProvider.Info("Started..");
try
{
_service.Calculate();
}
catch (Exception ex)
{
_logProvider.Error("Error " + ex);
}
}
Thanks
The simple answer is: yes, it will execute on next iteration.
Actually this is related to general .NET exception handling, rather then quartz.net behaviour:
if you have function that catches any exceptions - exceptions will not be visible outside of that function. In other words, code like
public void SomeMethod()
{
try
{
//some logic that can generate exception
}
catch (Exception ex)
{
}
}
is the same as
public void SomeMethod()
{
//some logic that NEVER generates the exception
}
In scope of quartz.net:
The only type of exception that you are allowed to throw from the execute method is JobExecutionException.
otherwise you will have unhandled exception in AppDomain. You can find more in Quartz.net Job unhandled exception behaviour SO question
I have been reading about exceptions for the past couple of hours and have a basic understanding. However the book I'am reading hasn't got the best examples when it comes to showcasing the coding aspects. I know that if I have code that could fail I wrap it in a try block and the catch the exceptions specifically i.e FormatException etc.
However the confusing part is when it comes to call stack were for e.g Method A calls Method B and Method B calls method C etc.
For example a exception occurs in Method c but it doesn't have a catch handler so it propagates back to the calling method so on and so fourth until one way or another the exception is handled.
What I was wondering is does execution continue in the method that caused the error or does execution continue in the method that handles the error.
Any basic examples would be great.
I won't repeat what the other answers have already said, but one other thing to point out is that any finally blocks will be executed after the catch statement happens, but before the exception is re-thrown down the stack. In other words, finally blocks are executed from the top of the stack, down.
For example:
static void Main(string[] args)
{
try
{
Crash(); // Causes a crash
}
catch
{
Console.WriteLine("Third"); // Exception re-thrown, this runs third
}
finally
{
Console.WriteLine("Fourth"); // Run last
}
// Code will continue here when all is done
}
static void Crash()
{
try
{
throw new ApplicationException();
}
catch
{
Console.WriteLine("First"); // This runs first
throw; // Re-throw exception
}
finally
{
Console.WriteLine("Second"); // This gets run second
}
Console.WriteLine("This will never execute..");
}
Will output First, then Second, Third, Fourth.
What I was wondering is does execution continue in the method that caused the error or does execution continue in the method that handles the error.
Second one is correct.For example in your B method if there is exception thrown and not handled,it goes to the caller method for example A,and if A handles that exception program will continue execution from that method.Consider this example:
private static void Main(string[] args)
{
A();
}
static void A()
{
try
{
B();
}
catch (Exception ex)
{
Console.WriteLine("Exception is thrown by {0} method and handled in A method.",ex.TargetSite);
}
Console.WriteLine("We are still in A method...");
}
static void B()
{
throw new Exception();
Console.WriteLine("We can't see this...");
}
This will produce the output:
// Exception is thrown by B() method and handled in A method.
// We are still in A method...
I have an Async method returning a Task.
I also wish to offer a synchronous equivalent, but I don't want consumers of it to have to go unpacking AggregateExceptions.
Now I understand that the whole idea is that you couldn't arbitrarily pick one in a general way, and I know I could go read loads more Stephen Toub articles (I will, but not now) and I'll understand it all and can decide for myself.
In the interim, I want to use the fact that my tasks are actually just chained 'workflows' without parallelism, just intervening Waits (no, not TPL DataFlow) which shouldnt not result in more than one exception. In that case, would it be appropriate to handle as follows:
CallAsync().Wait();
}
catch( AggregateException ae)
{
throw ae.Flatten().First()
or am I guaranteed that an AggregateException always has an InnerException even if there are more than one. Or is there a case where I should fall back to .Flatten().First() ?
In some TPL docs, I see a reference to an Unwrap() method on AggregateException (not sure if it was an extension or something in a beta release).
As a placeholder, I'm doing:
void Call( )
{
try
{
CallAsync().Wait();
}
catch ( AggregateException ex )
{
var translated = ex.InnerException ?? ex.Flatten().InnerExceptions.First();
if ( translated == null )
throw;
throw translated; }
}
Task CallAsync(){ ...
There's no "clean" way to do this that I know of. You can't use throw someInnerException; because you'll lose the stack wherever the exception originated in the the async workflow and if you just use throw; you're obviously going to propagate the AggregateException. What you would have to do for the synchronous method is have some kind of "wrapper" exception that you can stuff the first exception of the AggregateException into and then throw that consistently from the synchronous version of the method.
void Call()
{
try
{
CallAsync().Wait();
}
catch (AggregateException ex)
{
throw new MyConsistentWrapperException("An exception occurred while executing my workflow. Check the inner exception for more details.", ex.Flatten().InnerExceptions.First());
}
}
FWIW, they've solved this in 4.5 with the new ExceptionDispatchInfo class which will help you marshal exceptions across threads without whacking the stack. Then you could write the synchronous version like this:
void Call()
{
try
{
CallAsync().Wait();
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.Flatten().InnerExceptions.First()).Throw();
}
}
I was wondering if someone could help, I am relatively new to programming C#, here is the code that is causing a StackOverflowException:
private void createButton_Click(object sender, RoutedEventArgs e)
{
try
{
MeWhoService.Account NewAccount = new MeWhoService.Account();
NewAccount.AccountID = Guid.NewGuid();
NewAccount.LastName = LastNameTextBox.Text.Trim();
NewAccount.FirstName = FirstNameTextBox.Text.Trim();
NewAccount.EmailAddress = EMailAddressTextBox.Text.Trim();
NewAccount.Password = PasswordTextBox.Password.Trim();
NewAccount.ConfirmPassword = ConfirmPasswordTextBox.Password.Trim();
// Set Password
if (ValidatePassword())
{
NewAccount.Password = PasswordTextBox.Password.Trim();
viewModel.Create(NewAccount);
NavigationService.Navigate(App.MeAndWhoUri);
}
else
{
MessageBox.Show("Your Passwords don't match.");
}
}
catch (Exception excp)
{
MessageBox.Show(excp.Message);
}
}
Debugging a StackOverflowException in .NET is simple. Start the program in debug, do whatever it is that happens to cause the exception, wait until the exception is thrown and then look at the stack trace. Your stack trace will have a pattern to it showing any number of repeating method calls. Figure out which one of the method calls should not be calling another one in the stack trace and your error will go away.
If you can't find the pattern in your stack trace, include it in your question and I'm sure someone here will be able to help you.
is there a good general policy for setting up the sequence of catch blocks?
I would catch the most "specific" exception first, then further down catch the more general ones:
try {
...
}
catch (DivideByZeroException ex) {
...
}
catch (InvalidArgumentException ex) {
...
}
catch (Exception ex) {
...
}
Here are some design guidelines from MSDN. It might also be good to check out the Enterprise Library exception handling block. Lots of good stuff there for architecting an exception handling strategy.