Catch exception in calling method within method chaining in C# - c#

In recent interview, Interviewer ask me following question in C#.
Suppose we have 5 methods m1, m2, m3, m4, m5 and m1 call m2, m2 calls m3, and so on. But when exception occurs in m5 we must catch in m4, when exception occurs in m4 we must catch in m3, and so on. At first, I think it simple way, just include try-catch block in all methods excepts last method m5. But within seconds, i understand that this solution will not work.
public static void m1()
{
try
{
m2();
}
catch(Exception ex)
{
Console.WriteLine("From Catch m1");
}
}
public static void m2()
{
try
{
m3();
}
catch (Exception ex)
{
Console.WriteLine("From Catch m2");
}
}
public static void m3()
{
try
{
m4();
}
catch (Exception ex)
{
Console.WriteLine("From Catch m3");
}
}
public static void m4()
{
try
{
m5();
}
catch (Exception ex)
{
Console.WriteLine("From Catch m4");
}
}
public static void m5()
{
int i = 0;
Console.WriteLine(50 / i);
}
I also tried with many approaches, searched on internet but can't find proper solution. Please suggest correct way of doing this functionality.

Related

Does method overload work with exception types?

using System;
// Custom Exception types
class AException : Exception
{
}
class BException : Exception
{
}
class Test
{
public static void Main(string[] args)
{
try
{
throw new AException();
}
catch (Exception ex)
{
Callme(ex);
}
}
public static void Callme(AException aexception) {}
public static void Callme(BException bexception) {}
public static void Callme(Exception ex) {}
}
Callme(ex) will always call Callme(Exception ex) instead of Callme(AException ..) .. Is this an expected behavior. I read method overload resolution do work with inheritance relationships.
there is a more accepted way of doing this. try the following:
try
{
throw new AException();
}
catch (AException aex)
{
Callme(aex);
}
catch (BException bex)
{
Callme(bex);
}
catch (Exception ex)
{
Callme(ex);
}

Exit the function/method if an exception occurs

I'm trying to find a code to exit the whole method if an exception occurs in a sub method. I tried adding return in catch section of Subfunction() but the process will continue to Thirdfunction()
public static void Mainfunction()
{
try
{
//some code
//some code
Subfunction();
ThirdFunction();
}
catch(Exception ex)
{
//write to log
}
}
public static void Subfunction()
{
try
{
//some code
//some code
}
catch (Exception ex)
{
//write to log
}
}
So basically if an error occured in the Subfuntion() I want to stop the process from the Mainfunction() without continuing to the ThirdFunction(). Any help will be highly appreciated. Thanks
if an error occured in the Subfuntion() I want to stop the process
from the Mainfunction()
The simplest way to remove try/catch in your method Subfunction
If you want to keep the try/catch in this method, (for logging or something), rethrown exception
public static void Main()
{
try
{
Subfunction();
Thirdfunction();
}
catch(Exception ex)
{
}
}
public static void Subfunction()
{
try
{
throw new AccessViolationException();
}
catch (Exception ex)
{
throw;
}
}
There are basically two sets of possible solutions: With use of Exceptions and without.
With the use of exceptions, I'd recommend to just let it bubble up , as I've already said in comments.
Then you can rethrow:
try {
// exception here
}
catch(Exception ex)
{
throw;
// Attention: this is _different_ from "throw ex" !!
}
Pay attention here:
You can also use the throw e syntax in a catch block to instantiate a new exception that you pass on to the caller. In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.
See throw (C# Reference) (emphasis by me)
Coming over from Java myself, this is something people like myself will trip over during transitioning from Java to .Net. So if you got "java guys" new on the team: don't be harsh on them, just point them to the docs.
You can wrap:
try {
// exception here
}
catch(Exception inner)
{
throw new MyCustomException( "Some custom message", inner);
}
BTW: It is generally not a good idea to catch Exception. Most of the time you'd want to catch specific exceptions that you can actually handle.
The other class of solutions is without bubbling up exceptions:
Return value:
public static bool Subfunction()
{
bool success = true;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = false;
}
return success;
}
Or with return or error codes:
// DO NOT USE MAGIC NUMBERS !
private static readonly int SUCCESS_INDICATOR = 0;
private static readonly int ERROR_INDICATOR = 1;
// TODO DOCUMENT which errorcodes can be expected and what they mean!
public static int Subfunction()
{
int success = SUCCESS_INDICATOR;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = ERROR_INDICATOR;
}
return success;
}
Especially with "C-Guys" on the team you may stumble across this one. (No offense - just my experience)
Or with a state object ...
public static void Mainfunction()
{
try
{
//some code
//some code
ISuccessIndicator success = new ISIImplementation();
Subfunction( success );
if( !succes.HasException )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThrirdFunction or "else" branch are caught here.
}
}
public static void Subfunction( ISuccessIndicator result )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
result.HasException=true;
result.Exception = ex;
}
}
public interface ISuccessIndicator
{
Exception Exception {get; set;}
bool HasException {get; set;}
}
And if you are really crazy you could ...
public static void Mainfunction()
{
try
{
//some code
//some code
Exception ex = null;
Subfunction( ref ex );
if( ex == null ) // or more modern: ( ex is null )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThirdFunction or "else" branch caught here.
}
}
public static void Subfunction( ref Exception outEx )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
outEx = ex;
}
}
Please mind, that I in no way would encourage using the latter. But it is possible ... and OP asked for possibilities.
Disclaimer: All snippets untested. Who finds errors can keep them (but please write a comment, so I can fix them).

Should i provide try/catch on each method, or just the main method?

My practice for over a year now is to provide a separate try/catch block for each method i am writing then throwing the Exception Object should a specific block of code fail. For Example:
void MainMethod()
{
try {
int num = Method1();
string str = Method3();
bool bln = Metho4();
} catch (Exception Ex) {
MessageBox.Show(Ex.Message);
}
}
int Method1() {
try {
return 123 + Method2();
} catch (Exception) {
throw;
}
}
int Method2() {
try {
return Convert.ToInt32("One Hundred"); // <-- Obviously would fail.
} catch (Exception) {
throw;
}
}
string Method3() {
try {
string str1 = "Hello ";
return str1 + 12345; // <-- Would also fail.
} catch(Exception) {
throw;
}
}
bool Method4() {
try {
return true;
} catch(Exception) {
throw;
}
}
Should i provide each and every method their own/separate try/catch blocks? Or would it be better if its just the Main Method that has the try/catch?
Thanks
It really depends on what you're trying to accomplish. I prefer to catch and handle at the 'root' level whenever possible.
In your case I would use try/catch in the MainMethod and only try/catch anywhere else if I would like to catch and handle a specific exception and possibly recover.

how to handle OverflowException in C#?

I need to handle OverflowException in method mul().
class B
{
short a, b;
public B(short a, short b) { this.a = a; this.b = b; }
public short mul()
{
try
{
return checked((short)(a * b));
}
catch (OverflowException exc) { Console.WriteLine(exc); }
}
}
class MainClass
{
public static void Main(string[] args)
{
B m1 = new B(1000, 500);
m1.mul();
}
}
But the above code gives the following error :Error CS0161: 'B.mul()': not all code paths return a value (CS0161)
What can I do to fix it?
Please, do not mix logic and UI; just put try {} catch {} to its proper place and everything will be clear:
class B
{
...
// Logic: multiply with possible Overflow exception
// Let us be nice and document the exception
///<exception cref="System.OverflowException">
///When a or (and) b are too large
///</exception>
public short mul()
{
// Do we know how to process the exception at the place?
// No. There're many reasonable responses:
// - stop execution
// - use some special/default value (e.g. -1, short.MaxValue)
// - switch to class C which operates with int (or BigInteger) etc.
// That's why we don't catch exception here
return checked((short)(a * b));
}
}
...
class MainClass
{
// UI: perform operation and show the result on the console
public static void Main(string[] args)
{
B m1 = new B(1000, 500);
try
{
m1.mul();
}
catch (OverflowException exc)
{
// Proper place to catch the exception: only here, at UI,
// we know what to do with the exception:
// we should print out the exception on the Console
Console.WriteLine(exc);
}
}
}
When exception is thrown you write something to console but don't return any value.
Your method return value is short so you should return some value in catch (because method should return some short value in every execution path or throw):
try
{
return checked((short)(a * b));
}
catch(OverflowException exc)
{
Console.WriteLine(exc);
throw;
}
mul() does not return a value when an exception is caught. Add a return statement to the catch block or at the end of the method:
public short mul()
{
try {
return checked((short)(a * b)); }
catch(OverflowException exc) {
Console.WriteLine(exc);
return 0; // or whatever
}
return 0; // this goes as well
}
You have to throw exception from catch block. For example:
catch(OverflowException exc)
{
Console.WriteLine(exc)
throw exc;
}

How to remove try...catch block from many different functions [duplicate]

This question already has answers here:
Is there a way to catch all unhandled exceptions thrown by a given class?
(6 answers)
Closed 8 years ago.
I have a lot of classes (WCF services) that contain several function. Now I need to handle errors, but I don't want to create a block try ... catch within each function (for error handling).
How can I make try...catch in any class (or something else) so that we catch errors but did not write the same block within each method?
There will always be some duplication of code but you can reduce it to one line
public static class ExceptionHandler
{
public static void Run(Action action)
{
try
{
a();
}
catch(Exception e)
{
//Do Something with your exception here, like logging
}
}
}
and then just call
ExceptionHandler.Run(yourAction);
you can add overloads for functions and what not but this approach is not ideal. As you may want to catch specific exceptions in certain cases.
Since you did not provide code specifically, I will write some sample code to make it more obvious. If you have this:
public class MyClass
{
public void Method1ThatCanThrowException()
{
try
{
// the Method1 code that can throw exception
}
catch (MySpecificException ex)
{
// some specific error handling
}
}
public object Method2ThatCanThrowException()
{
try
{
// the Method2 code that can throw exception
}
catch (MySpecificException ex)
{
// the same specific error handling
}
}
}
So, if you intend to have single place error handling, you can use lambda, and the help of a private method:
private T CheckAndCall<T>(Func<T> funcToCheck)
{
try
{
return funcToCheck();
}
catch (MySpecificException ex)
{
// the old specific error handling
}
}
Notice the use of the Func<T> delegate. This is because you may need to wrap the try-catch logic around some code that can return a value.
Then you can rewrite the above methods like this:
public void Method1ThatCanThrowException()
{
CheckAndCall(
() =>
{
// the Method1 code that can throw exception
return null;
});
}
public object Method2ThatCanThrowException()
{
return CheckAndCall(
() =>
{
// the Method2 code that can throw exception
return someObject;
});
}
For example, rather than having to do this:
public class Program
{
public static string ReadFile(string filename)
{
//A BCL method that throws various exceptions
return System.IO.File.ReadAllText(filename);
}
public static void Main(string[] args)
{
try
{
Console.Write(ReadFile("name.txt"));
}
catch (Exception e)
{
Console.WriteLine("An error occured when retrieving the name! {0}", e.Message);
}
try
{
Console.Write(ReadFile("age.txt"));
}
catch (Exception e)
{
Console.WriteLine("An error occured when retrieving the age! {0}", e.Message);
}
}
}
You could implement a "Try..." method, using the ref or out keyword as appropriate:
public class Program
{
public static bool TryReadFile(string filename, out string val)
{
try
{
val = System.IO.File.ReadAllText(filename);
return true;
}
catch (Exception)
{
return false;
}
}
public static void Main(string[] args)
{
string name, age;
Console.WriteLine(TryReadFile("name.txt", out name) ? name : "An error occured when retrieving the name!");
Console.WriteLine(TryReadFile("age.txt", out age) ? age: "An error occured when retrieving the age!");
}
}
The downside to this approach is that you can't act upon a specific exception, but in the case of simply determining if an operation has or has not succeeded, I find this to be a syntactically clean approach.

Categories