Catch Block Error Handling

R

R. K. Wijayaratne

Hi everyone,

Can I please get your valuable feedback on the below. It is also
available here with clearer formatting http://coding-help.blogspot.com/

Shows a good way to handle errors that may occur inside the catch
block, for example while logging the original error.

[C#]

// ----------------------------------------------
// From: http://coding-help.blogspot.com/
// Title: Catch Block Error Handling
// Date: 10 July 2007
// Author: R. K. Wijayaratne
//
// Create a new C# file, e.g. "Program.cs",
// copy and paste the code below into it and save.
// To compile it open the .NET Framework command
// prompt and type:
//
// csc C:\MyPath\Program.cs
//
// where "C:\MyPath\" is the path of the C# file.
// If there are any errors correct them. To run
// the program type "Program" and press "Enter."
// ----------------------------------------------

using System;

public class Tester
{
// Program entry point.
static void Main(string[] args)
{
// Start running the test.
Tester.StartTest();
}

// Test driver method.
public static void StartTest()
{
try
{
// Test error handling.
TestHelper.TestErrorHandling();
}
catch (Exception exc)
{
// Output errors to console.
Console.Write(exc.ToString());
}
}
}

public class TestHelper
{
public static void TestErrorHandling()
{
try
{
// Try to do some work.
// Doing some working...
// Simulate error.
throw new InvalidOperationException();
}
catch (InvalidOperationException invOpExc)
{
string errDesc = "An invalid operation"
+ " occurred while doing some work.";
string extraErrs = null;

try
{
// Try to log original error.
// Logging original error...
// Simulate new error.
throw new SystemException();
}
catch (SystemException sysExc)
{
extraErrs += "\n\nAdditional error"
+ " occurred while"
+ " logging:\n\n"
+ sysExc.ToString();
}

try
{
// Try to email original error.
// Emailing original error...
// Simulate new error.
throw new ArgumentException();
}
catch (ArgumentException argOutOfRngExc)
{
extraErrs += "\n\nAdditional"
+ " error occurred"
+ " while emailing:\n\n"
+ argOutOfRngExc.ToString();
}

errDesc = string.Format("{0}\n\n====="
+ "{1}\n\n=====\n\n",
errDesc, extraErrs);

throw new Exception(errDesc, invOpExc);
}
}
}



CONSOLE OUTPUT

System.Exception: An invalid operation occurred while doing some work.

=====

Additional error occurred while logging:

System.SystemException: System error.
at TestHelper.TestErrorHandling()

Additional error occurred while emailing:

System.ArgumentException: Value does not fall within the expected
range.
at TestHelper.TestErrorHandling()

=====

---> System.InvalidOperationException: Operation is not valid due to
the current state of the object.
at TestHelper.TestErrorHandling()
--- End of inner exception stack trace ---
at TestHelper.TestErrorHandling()
at Tester.StartTest()


Thanks,

RKW.
 
N

Nicholas Paldino [.NET/C# MVP]

If you have an exception that is thrown inside the catch block, then
quite frankly, it is time to give up. The thing is, you can always have
"one more catch block" to catch any possible exception.

If the problem is repeatable (say for example, you are trying to log the
exception to a file and you don't have rights to the file you want to write
to) then you end up with a "poison" message, and you will end up executing
the extra catch blocks in vain. It doesn't matter how many you add, they
won't solve the problem.

That's why it is better to just exit if you have an exception thrown in
your catch block.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

R. K. Wijayaratne said:
Hi everyone,

Can I please get your valuable feedback on the below. It is also
available here with clearer formatting http://coding-help.blogspot.com/

Shows a good way to handle errors that may occur inside the catch
block, for example while logging the original error.

[C#]

// ----------------------------------------------
// From: http://coding-help.blogspot.com/
// Title: Catch Block Error Handling
// Date: 10 July 2007
// Author: R. K. Wijayaratne
//
// Create a new C# file, e.g. "Program.cs",
// copy and paste the code below into it and save.
// To compile it open the .NET Framework command
// prompt and type:
//
// csc C:\MyPath\Program.cs
//
// where "C:\MyPath\" is the path of the C# file.
// If there are any errors correct them. To run
// the program type "Program" and press "Enter."
// ----------------------------------------------

using System;

public class Tester
{
// Program entry point.
static void Main(string[] args)
{
// Start running the test.
Tester.StartTest();
}

// Test driver method.
public static void StartTest()
{
try
{
// Test error handling.
TestHelper.TestErrorHandling();
}
catch (Exception exc)
{
// Output errors to console.
Console.Write(exc.ToString());
}
}
}

public class TestHelper
{
public static void TestErrorHandling()
{
try
{
// Try to do some work.
// Doing some working...
// Simulate error.
throw new InvalidOperationException();
}
catch (InvalidOperationException invOpExc)
{
string errDesc = "An invalid operation"
+ " occurred while doing some work.";
string extraErrs = null;

try
{
// Try to log original error.
// Logging original error...
// Simulate new error.
throw new SystemException();
}
catch (SystemException sysExc)
{
extraErrs += "\n\nAdditional error"
+ " occurred while"
+ " logging:\n\n"
+ sysExc.ToString();
}

try
{
// Try to email original error.
// Emailing original error...
// Simulate new error.
throw new ArgumentException();
}
catch (ArgumentException argOutOfRngExc)
{
extraErrs += "\n\nAdditional"
+ " error occurred"
+ " while emailing:\n\n"
+ argOutOfRngExc.ToString();
}

errDesc = string.Format("{0}\n\n====="
+ "{1}\n\n=====\n\n",
errDesc, extraErrs);

throw new Exception(errDesc, invOpExc);
}
}
}



CONSOLE OUTPUT

System.Exception: An invalid operation occurred while doing some work.

=====

Additional error occurred while logging:

System.SystemException: System error.
at TestHelper.TestErrorHandling()

Additional error occurred while emailing:

System.ArgumentException: Value does not fall within the expected
range.
at TestHelper.TestErrorHandling()

=====

---> System.InvalidOperationException: Operation is not valid due to
the current state of the object.
at TestHelper.TestErrorHandling()
--- End of inner exception stack trace ---
at TestHelper.TestErrorHandling()
at Tester.StartTest()


Thanks,

RKW.
 
R

R. K. Wijayaratne

If an exception is throw inside the catch block, it overrides and
masks the exception that was originally thrown. Because the original
error is hidden by the new one, there is no way to find out what
actually happened in the first place. So for this reason it does make
sense to take this approach; as the caller will be able to descern
what the original error was and ALSO is made aware of any subsequent
errors as well, so corrective measure can be taken in ALL cases.

While this approach does not recity the problem, which is difficult to
do with any approach, it does give ALL the information needed to
rectify the problems at hand.

Notice that after capturing all the information it throws the error up
to the caller so they can decide what to do with it. The caller can
decide whether to continue processing or to quit.

throw new Exception(errDesc, invOpExc);

Also there maybe situations where you cannot simply quit.

RKW.

PS. Logging and emailing are used as examples for the catch block
processing just for demonstrating the concept; but it could equally
apply to any call inside the catch block that can throw exceptions.


If you have an exception that is thrown inside the catch block, then
quite frankly, it is time to give up. The thing is, you can always have
"one more catch block" to catch any possible exception.

If the problem is repeatable (say for example, you are trying to log the
exception to a file and you don't have rights to the file you want to write
to) then you end up with a "poison" message, and you will end up executing
the extra catch blocks in vain. It doesn't matter how many you add, they
won't solve the problem.

That's why it is better to just exit if you have an exception thrown in
your catch block.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)



Hi everyone,
Can I please get your valuable feedback on the below. It is also
available here with clearer formattinghttp://coding-help.blogspot.com/
Shows a good way to handle errors that may occur inside the catch
block, for example while logging the original error.

// ----------------------------------------------
// From:http://coding-help.blogspot.com/
// Title: Catch Block Error Handling
// Date: 10 July 2007
// Author: R. K. Wijayaratne
//
// Create a new C# file, e.g. "Program.cs",
// copy and paste the code below into it and save.
// To compile it open the .NET Framework command
// prompt and type:
//
// csc C:\MyPath\Program.cs
//
// where "C:\MyPath\" is the path of the C# file.
// If there are any errors correct them. To run
// the program type "Program" and press "Enter."
// ----------------------------------------------
using System;
public class Tester
{
// Program entry point.
static void Main(string[] args)
{
// Start running the test.
Tester.StartTest();
}
// Test driver method.
public static void StartTest()
{
try
{
// Test error handling.
TestHelper.TestErrorHandling();
}
catch (Exception exc)
{
// Output errors to console.
Console.Write(exc.ToString());
}
}
}
public class TestHelper
{
public static void TestErrorHandling()
{
try
{
// Try to do some work.
// Doing some working...
// Simulate error.
throw new InvalidOperationException();
}
catch (InvalidOperationException invOpExc)
{
string errDesc = "An invalid operation"
+ " occurred while doing some work.";
string extraErrs = null;
try
{
// Try to log original error.
// Logging original error...
// Simulate new error.
throw new SystemException();
}
catch (SystemException sysExc)
{
extraErrs += "\n\nAdditional error"
+ " occurred while"
+ " logging:\n\n"
+ sysExc.ToString();
}
try
{
// Try to email original error.
// Emailing original error...
// Simulate new error.
throw new ArgumentException();
}
catch (ArgumentException argOutOfRngExc)
{
extraErrs += "\n\nAdditional"
+ " error occurred"
+ " while emailing:\n\n"
+ argOutOfRngExc.ToString();
}
errDesc = string.Format("{0}\n\n====="
+ "{1}\n\n=====\n\n",
errDesc, extraErrs);
throw new Exception(errDesc, invOpExc);
}
}
}
CONSOLE OUTPUT
System.Exception: An invalid operation occurred while doing some work.

Additional error occurred while logging:
System.SystemException: System error.
at TestHelper.TestErrorHandling()
Additional error occurred while emailing:
System.ArgumentException: Value does not fall within the expected
range.
at TestHelper.TestErrorHandling()

---> System.InvalidOperationException: Operation is not valid due to
the current state of the object.
at TestHelper.TestErrorHandling()
--- End of inner exception stack trace ---
at TestHelper.TestErrorHandling()
at Tester.StartTest()

RKW.- Hide quoted text -

- Show quoted text -
 
R

R. K. Wijayaratne

It is also a good to throw the error up to the caller ONLY if the
original error was un-hadled inside the catch block, as the modified
code fragment below shows. You can find the complete listing for this
modification here http://coding-help.blogspot.com/2007/07/catch-block-error-handling.html

try
{
// Try to do some work.
// Doing some work...
// Simulate error.
throw new InvalidOperationException();
}
catch (InvalidOperationException invOpExc)
{
string errDesc = "An invalid operation"
+ " occurred while doing some work.";
string extraErrs = null;
bool handled = true;

try
{
// Try to log original error.
// Logging original error...
// Simulate new error.
throw new SystemException();
}
catch (SystemException sysExc)
{
handled = false;
extraErrs += "\n\nAdditional error"
+ " occurred while"
+ " logging:\n\n"
+ sysExc.ToString();
}

try
{
// Try to email original error.
// Emailing original error...
// Simulate new error.
throw new ArgumentException();
}
catch (ArgumentException argExc)
{
handled = false;
extraErrs += "\n\nAdditional"
+ " error occurred"
+ " while emailing:\n\n"
+ argExc.ToString();
}

// Throw it up to caller if not handled.
if (!handled)
{
errDesc = string.Format("{0}\n\n====="
+ "{1}\n\n=====\n\n",
errDesc, extraErrs);

throw new Exception(errDesc, invOpExc);
}
}


If an exception is throw inside the catch block, it overrides and
masks the exception that was originally thrown. Because the original
error is hidden by the new one, there is no way to find out what
actually happened in the first place. So for this reason it does make
sense to take this approach; as the caller will be able to descern
what the original error was and ALSO is made aware of any subsequent
errors as well, so corrective measure can be taken in ALL cases.

While this approach does not recity the problem, which is difficult to
do with any approach, it does give ALL the information needed to
rectify the problems at hand.

Notice that after capturing all the information it throws the error up
to the caller so they can decide what to do with it. The caller can
decide whether to continue processing or to quit.

throw new Exception(errDesc, invOpExc);

Also there maybe situations where you cannot simply quit.

RKW.

PS. Logging and emailing are used as examples for the catch block
processing just for demonstrating the concept; but it could equally
apply to any call inside the catch block that can throw exceptions.

If you have an exception that is thrown inside the catch block, then
quite frankly, it is time to give up. The thing is, you can always have
"one more catch block" to catch any possible exception.
If the problem is repeatable (say for example, you are trying to log the
exception to a file and you don't have rights to the file you want to write
to) then you end up with a "poison" message, and you will end up executing
the extra catch blocks in vain. It doesn't matter how many you add, they
won't solve the problem.
That's why it is better to just exit if you have an exception thrown in
your catch block.
Hi everyone,
Can I please get your valuable feedback on the below. It is also
available here with clearer formattinghttp://coding-help.blogspot.com/
Shows a good way to handle errors that may occur inside the catch
block, for example while logging the original error.
[C#]
// ----------------------------------------------
// From:http://coding-help.blogspot.com/
// Title: Catch Block Error Handling
// Date: 10 July 2007
// Author: R. K. Wijayaratne
//
// Create a new C# file, e.g. "Program.cs",
// copy and paste the code below into it and save.
// To compile it open the .NET Framework command
// prompt and type:
//
// csc C:\MyPath\Program.cs
//
// where "C:\MyPath\" is the path of the C# file.
// If there are any errors correct them. To run
// the program type "Program" and press "Enter."
// ----------------------------------------------
using System;
public class Tester
{
// Program entry point.
static void Main(string[] args)
{
// Start running the test.
Tester.StartTest();
}
// Test driver method.
public static void StartTest()
{
try
{
// Test error handling.
TestHelper.TestErrorHandling();
}
catch (Exception exc)
{
// Output errors to console.
Console.Write(exc.ToString());
}
}
}
public class TestHelper
{
public static void TestErrorHandling()
{
try
{
// Try to do some work.
// Doing some working...
// Simulate error.
throw new InvalidOperationException();
}
catch (InvalidOperationException invOpExc)
{
string errDesc = "An invalid operation"
+ " occurred while doing some work.";
string extraErrs = null;
try
{
// Try to log original error.
// Logging original error...
// Simulate new error.
throw new SystemException();
}
catch (SystemException sysExc)
{
extraErrs += "\n\nAdditional error"
+ " occurred while"
+ " logging:\n\n"
+ sysExc.ToString();
}
try
{
// Try to email original error.
// Emailing original error...
// Simulate new error.
throw new ArgumentException();
}
catch (ArgumentException argOutOfRngExc)
{
extraErrs += "\n\nAdditional"
+ " error occurred"
+ " while emailing:\n\n"
+ argOutOfRngExc.ToString();
}
errDesc = string.Format("{0}\n\n====="
+ "{1}\n\n=====\n\n",
errDesc, extraErrs);
throw new Exception(errDesc, invOpExc);
}
}
}
CONSOLE OUTPUT
System.Exception: An invalid operation occurred while doing some work.
=====
Additional error occurred while logging:
System.SystemException: System error.
at TestHelper.TestErrorHandling()
Additional error occurred while emailing:
System.ArgumentException: Value does not fall within the expected
range.
at TestHelper.TestErrorHandling()
=====
---> System.InvalidOperationException: Operation is not valid due to
the current state of the object.
at TestHelper.TestErrorHandling()
--- End of inner exception stack trace ---
at TestHelper.TestErrorHandling()
at Tester.StartTest()
Thanks,
RKW.- Hide quoted text -
- Show quoted text -- Hide quoted text -

- Show quoted text -
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top