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;
}
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.
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 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;
}
I have a question about Try Catch statements in C#.
For example if I had a statement as such
try
{
string text = sometext;
var Auto_IMPORT = new AutoImport();
Auto_IMPORT.StartProcessing();
Console.WriteLine(sometext);
}
catch(Exception Ex)
{
//Would this catch AutoImport.StartProcessing() exceptions?
Console.WriteLine(ex.Message);
}
AutoImport is a Class Library and i'm calling some logic to start processing.
If an exception occurred within the logic inside AutoImport.StartProcessing() would this try statement catch that exception or would it be out of scope by then?
Thanks In Advance
It depends on the behavior of Auto_IMPORT.StartProcessing(). If no exception is caught in it, then yes, you will get an exception. On the other hand, if the internal code off Auto_IMPORT catches the exception, and doesn't throw a new exception, then you wont get any exceptions.
Yes.
It catches any errors that are in the try block. Doesn't matter if they're in some method of some class.
Tested with:
class _Class
{
public string name;
public void myMethod()
{
int i;
string s = "asda";
i = int.Parse(s);
}
}
class Program
{
static void Main(string[] args)
{
try
{
_Class blah = new _Class();
blah.name = "Steve";
blah.myMethod();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
Caught exception at int.Parse
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.