exceptions handling after button click event - c#

Im trying to stop processing after an exception is found and displayed it to the user but i cant get my code to stop once one has been found...
try
{
//Someting
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
//// STOP CODE WHEN EXCEPTION IS FOUND SO USER CAN FIX THE CAUSE
}
finally
{
Response.Redirect("//hud/account.aspx");
}
i have tried throw and return commands with no luck. Im new to all of this and i have googled it with no luck... any ideas what im missing ? or maybe i have the wrong idea all together. its a button click event that is tied in with a textbox, when an exception is thrown it will display the error in a label for the user to resolve (too many numbers...etc ). When corrected and the button is clicked again, this time without throwing an exception the users should be redirected. Any help would be great.

not use finally.
try
{
//Someting
Response.Redirect("//hud/account.aspx");
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
//// STOP CODE WHEN EXCEPTION IS FOUND SO USER CAN FIX THE CAUSE
}

You should not be using exceptions to do validation or flow-of-control. You should simply check the conditions in the code and present a message if the values don't satisfy the conditions.
e.g.
int foo;
if( !Int32.TryParse( something.Text, out foo ) )
{
lblError.Text = "You must enter a number.";
}
else
{
Response.Redirect...
}

You should remove the redirect logic from the finally block. Because finally block always gets executed weather an exception has encountered or not.
Probably you should try something as listed below by #user3401335. He has moved the redirect as the last statement in the try block. Your core logic stays on the top and if it is successful and no exception has encountered then it allows you to redirect. Otherwise it stops you right there with the help of exception code...
You should try as follows:
try
{
//Something
Response.Redirect("//hud/account.aspx");
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
// STOP CODE WHEN EXCEPTION IS FOUND SO USER CAN FIX THE CAUSE
}
finally
{
// PUT IN SOMETHING HERE THAT YOU WANT ALWAYS TO GET EXECUTED
}

Try this code:
bool iserror = false;
try
{
int a = 0;
int b = 1;
int c = b / a;
Response.Redirect("//hud/account.aspx");
}
catch (Exception ex)
{
lblerror.Text = (ex.Message);
iserror = true;
}
finally
{
if (!iserror)
{
//do something if you want
}
}

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.

Is it possible to understand which block(try or catch) was called before finally block?

I have a try-catch-finally block like below and I need to log the process's result in the finally block. So I need to know the result in finally block to be able to do it.
var isSucceed = false;
try
{
Do();
isSucceed = true;
}
catch(Exception ex)
{
isSucceed = false;
}
finally
{
_logger.LogInformation($"The process has been completed. Is Succeed = {isSucceed}");
}
So is there any property or method which provides if try block was called?
try
{
Do();
}
catch(Exception ex)
{
}
finally
{
var isSucceed = <isTryCalled>;
_logger.LogInformation($"The process has been completed. Is Succeed = {isSucceed}");
}
No - but you can safe the exception beforehand:
Exception error;
try
{
Do();
}
catch (ArgumentNullException ex)
{
// Safe the ex
error = ex;
}
catch (Exception ex)
{
// Safe the ex
error = ex;
}
finally
{
var isSucceed = error == null;
if (isSucceed)
_logger.LogInformation($"The process has been completed successfully");
else
_logger.LogError("The process faulted.", error);
}
The first piece of code you have seems to do what you want very well, but could probably do with some minimisation(a):
var succeeded = true;
try {
Do();
} catch(Exception ex) {
succeeded = false;
} finally {
// succeeded is false if exception happened.
}
But, to be honest, if you want to do something on exception, why not just do it in the exception block?
In any case, C# does not provide this information, you will have to maintain it yourself, as per the example.
(a) It may be preferable, in the case where you may add future exceptions, to assume failure and flag success at the end of the try block. That way, you don't have to remember to flag failure in every single except block. That option would be a minor change:
var succeeded = false;
try {
Do();
succeeded = true;
} catch(Exception1 ex) {
// No need to change succeeded here.
} catch(Exception2 ex) {
// Or here.
} catch(Exception3 ex) {
// Or, yes, you guessed it, here either :-)
} finally {
// succeeded is false if exception happened.
}
Of course, once you get to that point, you may also want to know which except block was triggered, so a simple boolean flag will not suffice. An enumeration is one possibility, another is storing the exception itself. Both of these would be initialised to "no exception" before the try block and then set to a specific value in each except block.
In that case, this footnoted solution (assuming a failure then having the try block flag success at the end) wouldn't work since you can't really assume a specific failure.

How to catch an exception only if another exception as not occured in C#

So I'm a student in programming and I want my code to do a try-catch on an exception but ONLY if another exception as not occured. Let me show you want I did:
using (var ctxInsert = new model())
{
CATEGORIES c1 = new CATEGORIES(6, "cat6", "category6");
Console.WriteLine("Please wait while rows are added to tables...");
//first try-catch to know if the new entry exist
try
{
ctxInsert.CATEGORIES.Add(c1);
}
catch (ModelValidationException e1)
{
Console.WriteLine(e1.Message);
Console.WriteLine("Category already exist");
}
//second try-catch to make sure saving changes to table is succesful
try
{
ctxInsert.SaveChanges();
Console.WriteLine(c1.NAME + " : Succesfuly added");
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("not done");
}
}
Console.ReadLine();
So what I'm trying to do is that the second try-catch block only runs if the first DIDN'T catch an exception. Cause right now, like this, both try-catch runs and it doesn't make sense to save changes if the first one catches an exception.
I tried a bunch of things on my own but nothing works...
If you need just to make your code working as you expected, you can write like this:
using (var ctxInsert = new model())
{
CATEGORIES c1 = new CATEGORIES(6, "cat6", "category6");
Console.WriteLine("Please wait while rows are added to tables...");
//first try-catch to know if the new entry exist
try
{
ctxInsert.CATEGORIES.Add(c1);
ctxInsert.SaveChanges();
Console.WriteLine(c1.NAME + " : Succesfuly added");
}
catch (ModelValidationException e1)
{
Console.WriteLine(e1.Message);
Console.WriteLine("Category already exist");
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("not done");
}
}
Console.ReadLine();
BUT, I'd rather write code without any try/catch but make exception interceptors on top level of your application (There are best practices, depending on what framework you are using)
The whole point of a try-catch is to stop an exception from preventing the rest of your code from executing. In your case, there are a few options I see off the top of my head:
Decide whether a try-catch is really what you're looking for - you could also have your method throw an exception and prevent execution of the rest of the code
Throw an exception in your catch, that way you get your logs and it tells the rest of the code that something went wrong, preventing execution
Use a variable which gets modified by the first catch, then conditionally execute the rest of the code based on that variable
Use a try-catch-finally
yes you can use the finally keyword let me show you with code example
using System;
namespace ErrorHandlingApplication {
class DivNumbers {
int result;
DivNumbers() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}

How to handle exceptions in MVVM View Model properties ?

How can i handle an exception that occurs when properties in my ViewModel get occurs? The property gets happen before the Loaded event. For example, I have a property (get-only) that calls some data method to return a collection of states to fill a combobox's itemsource. But sometimes SQL will not connect, and I get an exeption. There are multiple properties like this, I want to tell the user that the combos could not be loaded correctly and then just put them back at my home screen. However, i don'twant 5 message boxes if they all fail. Also, why does it continue to try to get the properties, even though i told it to go to the home screen when the first exception occured? Note: the GetStatesList() method also has try/catch and throw in the catch...
try
{
ObservableCollection<string> states=null;
// perform sql query
states=StateDat.Instance.GetStatesList(); //get the collection of state names
}
catch(Exception ex)
{
MessageBox.Show("Error"); //display an error message
MessengerInstance.Send(ViewModelNamesEnum.HomeVM); //go home
}
Have all the five statements continuously with in 1 try catch, instead of having try catch for each statement, so if exception occurs 2nd statement following 3 will not get executed and at any cost you will have only 1 msg box and you can return to the home screen as well without any issuse
Here is one way you could handle this..
Make separate methods for each property call.. and throw a custom exception to indicate something went wrong with that specific call..
Anyway the outer exception will make sure that if one fails, it bails out..
Method1() {
try {
//Code for Method1
}catch(Exception ex) { throw new CustomException(""); }
}
Method2() {
try {
//Code for Method2
}catch(Exception ex) { throw new CustomException(""); }
}
Method3() {
try {
//Code for Method3
}catch(Exception ex) { throw new CustomException(""); }
}
try {
Method1();
Method2();
Method3();
}catch(CustomException custom) {
// You would know specific reasons for crashing.. and can return meaningful message to UI.
} catch(Exception ex) {
//Anything that was un-handled
}
class CustomException : Exception {
//Implementation here..
}

How to determine if an exception is of a particular type

I have a piece of try catch code:
try
{
...
}
catch(Exception ex)
{
ModelState.AddModelError(
"duplicateInvoiceNumberOrganisation", "The combination of organisation and invoice number must be unique");
}
For this piece of code I'm trying to insert a record into a database: The dba has set it up so that the database checks for duplicates and returns an error if there are duplicates. Currently, as you can see, I'm adding the same error to the model no matter what error occurred. I want it changed so this error is only added to the model if it was caused by the duplicate error set up by the dba.
Below is the error I want to catch. Note it's in the inner exception. Can anyone tell me how to specifically catch this one?
before your current catch add the following:
catch(DbUpdateException ex)
{
if(ex.InnerException is UpdateException)
{
// do what you want with ex.InnerException...
}
}
From C# 6, you can do the following:
catch(DbUpdateException ex) when (ex.InnerException is UpdateException)
{
// do what you want with ex.InnerException...
}
Replace System.Threading.ThreadAbortException with your exception.
try
{
//assume ThreadAbortException occurs here
}
catch (Exception ex)
{
if (ex.GetType().IsAssignableFrom(typeof(System.Threading.ThreadAbortException)))
{
//what you want to do when ThreadAbortException occurs
}
else
{
//do when other exceptions occur
}
}
Not enough rep to comment. In response to #conterio question (in #Davide Piras answer):
is there a catch "when not" syntax?
There is.
catch (Exception e) when (!(e is ArgumentException)) { }
To get name of the exception you can use
catch (Exception exc){
if (exc.GetType().FullName == "Your_Exception")
{
// The same can be user for InnerExceptions
// exc.InnerException.GetType().FullName
}
}
You can take a look at the SQLException class -- and check for the contents of the exception's message if it contains what you now see in your inner exception..Something like this:
try
{
//your code here
}
catch (SQLException ex)
{
if (ex.Message.Contains("Cannot insert duplicate key in obj...."))
{
//your code here
}
}

Categories