As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have 3 Methods, I am try catch for every method. If an error occur in Third method it goes to exception.
private void M1()
{
try
{
//some code
//calling M2()
//some code
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void M2()
{
try
{
//some code
//calling M3()
//some code
}
catch(Exception ex)
{
throw ex;
}
}
private void M3()
{
try
{
//some code
//Error Occur
//some code
}
catch(Exception ex)
{
throw ex;
}
}
Now it goes directly to M1() method and shows Exception. And the another method is
private void M1()
{
try
{
//some code
//calling M2()
//some code
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void M2()
{
try
{
//some code
//calling M3()
//some code
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void M3()
{
try
{
//some code
//Error Occur
//some code
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After exception also it execute the code in M2() and in M1().
Which Program is best...,
There is nothing good or bad design, only your scenario decided the best approach.
If you want to catch the error on M1 then don't write Try .. catch in M2 and M3.
If you want to handle the error in the function where error was raised then put the Try .. catch in same function.
Related
This question already has answers here:
What happens if a finally block throws an exception?
(11 answers)
Exception thrown in catch and finally. CLR behavior vs. try-catch block [duplicate]
(2 answers)
Closed 3 months ago.
I have a code:
class Program
{
public static void Main()
{
try
{
Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static void Execute()
{
try
{
Step3();
}
catch (Exception ex)
{
Console.WriteLine("catch");
throw new Exception("1");
}
finally
{
Console.WriteLine("finally");
throw new Exception("2");
}
}
public static void Step3()
{
try
{
Console.WriteLine("Step 3");
throw new Exception("step 3");
}
finally
{
Console.WriteLine("Step 3 finally");
}
}
}
and output:
Step 3
Step 3 finally
catch
finally
2
I do not understand what happened with exception throw new Exception("1");. Did it just disappear? Why?
I have read answer about specification but I'm not sure I understand what happened with throw new Exception("1"); Is it still in memory?
I fully accept that this is essentially a repeat of question of
Catching custom exception in c#
That question is closed, so I hope to rephrase it as I am having the same problem.
I have a class that can be summarised thus..
[Serializable()]
public class DataFile : ISerializable
{
public DataFile()
{
// Data structures
}
public DataFile(SerializationInfo info, StreamingContext ctxt) : this()
{
if(true)
{
throw new VersionNotFoundException();
}
// Load data
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
// Save data
}
}
In my MainForm, I have a method that constains code equivilant to..
private DataFile Data;
private string CurrentFile = "C:\myfile.xyz";
private void LoadData()
{
try
{
using (Stream stream = File.Open(CurrentFile, FileMode.Open))
Data = (DataFile)new BinaryFormatter().Deserialize(stream);
}
catch (VersionNotFoundException e)
{
// never gets here
}
catch (Exception e)
{
// VersionNotFoundException gets caught here as an inner exception
}
}
My question(s)
Why would the VersionNotFoundException not get caught in the "catch (VersionNotFoundException e)" section (have I not added it to the top of the exception stack)? What am I doing wrong and how do I fix it? Why/how am I making an 'inner' exception and how do I stop it?
I was scratching my head with this and completely missed the comment.
// VersionNotFoundException gets caught here as an inner exception
You cannot catch inner exceptions like this, however you can use when in C#6 or later
try
{
}
catch (Exception e) when (e.InnerException is VersionNotFoundException e2)
{
Console.WriteLine(e2.Message);
}
catch (Exception e)
{
}
Demo here
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am trying to aim for a global try catch exception handler as I have several child class
methods that have try catches inside them. So basically I want the parent class method to catch all those
exceptions and log it.
One of the common ones are SQL exceptions.
What is the best approach here to create a common handler which will catch the errors?
Here is an example of what is going on in my application
public class Parent
{
public void ParentMethod()
{
try
{
var childClass = new Child();
var process = childClass.Process();
if (process)
{
// Do this
}
else
{
// raise new Exception
}
}
catch(Exception ex){
WriteToErrorLogger.Error(ex)
}
}
}
public class Child
{
public bool Process()
{
try{
// Do something and save to Database
}
catch (SqlException sqlEx)
{
// log exception
return false;
}
catch (Exception ex)
{
// log exception
return false;
}
}
}
What do you mean? What would make sense would be to do the exact opposite
public class Parent
{
public void ParentMethod()
{
try
{
var childClass = new Child();
var process = childClass.Process();
if (process)
{
// Do this
}
else
{
// raise new Exception
}
}
catch (SqlException sqlEx)
{
WriteToErrorLogger.Error(ex);
}
catch(Exception ex){
WriteToErrorLogger.Error(ex);
}
}
}
Child
public class Child
{
public bool Process()
{
// Do something and save to Database
}
}
If you want to conditionally do it, you could change the child like this
public class Child
{
public bool Process(bool rethrow = false)
{
try{
// Do something and save to Database
}
catch (SqlException sqlEx)
{
if(rethrow) throw;
// log exception
return false;
}
catch (Exception ex)
{
if(rethrow) throw
// log exception
return false;
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
using (var ss = new extest()) {
throw new Exception("Exception1");
}
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
}
class extest : IDisposable
{
public void Dispose()
{
throw new Exception("Exception2");
}
}
Run the codes result is "Exception2",
So I want to know how you can catch two exceptions, or just catch an Exception1.
My project has thousands of such using, which does not add try, but extest's Dispose is only one place, and I hope to know what exception has thrown before the Dispose.
Thanks
The problem in your example is that the second exception is thrown while the first exception is being handled. I.e. the using statement is effectively a try/finally pair, with the call to Dispose() in the finally block. So, the second exception supersedes the first one.
Having a Dispose() method that throws an exception is a very bad idea. So, the best solution here is to fix that. Don't throw an exception from a Dispose() method. But if you can't fix that for some reason and you want to see both, you need to make sure you're in a position to catch both. You can do this by adding another try/catch inside the using:
try
{
using (var ss = new extest()) {
try
{
throw new Exception("Exception1");
}
catch (Exception exInner)
{
System.Console.WriteLine(ex.Message);
throw;
}
}
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
}
The easiest way to handle this would be to rearrange your code:
static void Main(string[] args)
{
try
{
using (var ss = new extest())
{
try
{
CodeThatMightThrowAnException();
}
catch (Exception e)
{
// Process Exception here
}
}
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
Edit:
If the handling of the exceptions inside the using is always going to be the same, you could build a helper class that could make refactoring easier:
public class TryCatchHelper
{
public Exception Exception { get; private set; } = null;
public void Execute(Action action)
{
try
{
action()
}
catch (Exception e)
{
exception = e;
}
}
}
Then in your method:
static void Main(string[] args)
{
var helper = new TryCatchHelper();
try
{
using (var ss = new extest())
{
helper.Execute(() => {
// Your Code Block Here
});
}
}
catch(Exception ex)
{
// The Dispose threw an exception
}
if (helper.Exception != null)
{
// Handle the exception from the block here.
}
}
it's impossible to catch more than 1 exception.
when you throw Exception2 it should be catched in your catch clause. when you see "Exception2" it is printed by System.Console.WriteLine(ex.Message);. So, you can change the log in catch, or change the throwing exception message in Dispose.
reference added:
class Program
{
static void Main(string[] args)
{
try
{
using (var ss = new extest()) {
...
}
}
catch(Exception ex)
{
System.Console.WriteLine("extest error : " + ex.Message);
}
}
}
class extest : IDisposable
{
public void Dispose()
{
throw new Exception("Dispose failed: reason");
}
}
I have the following code:
catch (ServiceException e) { se(e); return View("CreateEdit", vm); }
catch (Exception e) { ex(e); return View("CreateEdit", vm); }
return RedirectToAction("ShowSummary", new {
ds = vm.Meta.DataSourceID
});
protected void se(ServiceException e) {
ModelState.Merge(e.Errors);
}
protected void ex(Exception e) {
Trace.Write(e);
ModelState.AddModelError("", "Database access error: " + e.Message);
}
I would like to change this to something like:
catch (Exception e) { processException(e); return View("CreateEdit", vm); }
Is there a way that I can add code to a processException function that would be able
to check what kind of exception it is and then do action depending on if it is a ServiceException
or just a general exception? I just want to put all my exception handling in one place
and then call it.
You can use the is keyword like this
protected void processException(Exception e) {
if (e is XXXException)
{
this.doThis();
}
else if (e is YYYException)
{
this.doThat();
}
}
You can also use a switch statement and test the type of the e but IMO is is easier and better
You can use the typeOf(e) or e.GetType() and then do a switch or if statement on that.
Absolutely, we use this extensively in database exception handling.
public void processException(Exception ex)
{
if (ex is System.Threading.ThreadAbortException)
{
// Do something
}
else if (ex is AnotherException)
{
// Do something else
}
}