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;
}
Related
First, I'm sorry about the title, i don't know how to explain my problem in the title.
I create a generality function:
public T DoSomething<T>(List<object> parameters, ref Exception exception, T _default = default(T), int tryTimes = 3, int waitingSeconds = 5) where T : new()
{
try {
// Do something
// return object T
return new T(); // this line for void function which does not need return.
}
catch (Exception ex) {
if (tryTimes > 0) {
tryTimes -= 1;
System.Threading.Thread.Sleep(waitingSeconds * 1000);
return DoSomething(parameters, ref exception, _default, tryTimes, waitingSeconds);
}
else {
exception = ex;
return _default;
}
}
}
and I have many normal functions like that:
public bool PingApi(string apiurl, ref Exception exception) {
try {
/// call to api
return true;
}
catch(Exception ex) {
exception = ex;
return false;
}
}
Can anyone help me to merge them to a greater generality function, please?
Reason for this function: Retry to do something when sure that the reason for catching (in this sample, if internet's connection is corrupted sometimes).
Thanks for reading.
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).
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.
I want to do something like this in C#. I think this is possible using Delegates or Anonymous Methods. I tried but I couldn't do it. Need help.
SomeType someVariable = try {
return getVariableOfSomeType();
} catch { Throw new exception(); }
You can create a generic helper function:
static T TryCatch<T, E>(Func<T> func, Func<E, T> exception)
where E : Exception {
try {
return func();
} catch (E ex) {
return exception(ex);
}
}
which you can then call like so:
static int Main() {
int zero = 0;
return TryCatch<int, DivideByZeroException>(() => 1 / zero, ex => 0);
}
This evaluates 1 / zero within the context of TryCatch's try, causing the exception handler to be evaluated which simply returns 0.
I doubt this will be more readable than a helper variable and try/catch statements directly in Main, but if you have situations where it is, this is how you can do it.
Instead of ex => 0, you can also make the exception function throw something else.
You should do something like this:
SomeType someVariable;
try {
someVariable = getVariableOfSomeType();
}
catch {
throw new Exception();
}
SomeType someVariable = null;
try
{
someVariable = GetVariableOfSomeType();
}
catch(Exception e)
{
// Do something with exception
throw;
}
You can try this
try
{
SomeType someVariable = return getVariableOfSomeType();
}
catch { throw; }
SomeType someVariable = null;
try
{
//try something, if fails it move to catch exception
}
catch(Exception e)
{
// Do something with exception
throw;
}
I am making a class for using in a winforms application in VC#
My question is how to return a catched exception to the caller out of the class? Take this as an example:
Public Class test
{
private int i = 0;
public test() { }
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
catch (Exception ex)
{
throw ex;
}
}
}
And imagine calling this method in another place while referencing to this class. Is that a good idea? Or how it should be done?
You have several options.
You could not handle the exception at all :
public SetInt()
{
i = "OLAGH"; //This is bad!!!
return i;
}
Then the caller will need to handle the exception.
If you want to handle the exception you can catch the error and handle it.
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
catch (FailException ex)
{
return FAIL;
}
}
Note that it is bad practice to just catch the base Exception class. You should anticipate which errors may occur and try to handle them. Unanticipated errors and the result of bugs and should make a big noise so that you can be alerted to other problems and fix them.
If you want to raise your own kind of exception, you could do :
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
catch (FailException ex)
{
throw new SetIntFailException ( ex );
}
}
Then it is the callers responsibility to handle the SetIntFailException rather than a CastFailException or whatever hundreds of other kind of exceptions your code may throw..
If you want the caller to handle the exception, but you have some clean up you want to do, you can use finally :
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
finally
{
// Cleanup.
}
}
The code in the finally block will always be called, even when there is an exception, but the error still gets raised to the caller.
I am assuming that in your real code, it will at least compile! ;-)
In the first place, the code won't compile.
public class test
{
private int i = 0;
public test(){}
public SetInt(object obj)
{
try
{
i = (int) obj;
return i;
}
catch(exception ex)
{
throw; // This is enough. throwing ex resets the stack trace. This maintains it
}
}
}
If you want to throw an exception do this:
throw new Exception ("My exception");
You can make a class derived from Exception if you want to hold some exception specific details.