How to shorten catch block

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Is there any way how I can shorten following code ?

try {...}
catch(FormatException) {SAME CODE IN ALL CATCH BLOCKS}
catch(OverflowException) {SAME CODE IN ALL CATCH BLOCKS}

E.g. to this ...

try {...}
catch(FormatException | OverflowException) {...}

Because I need write same code to all catch blocks ...

Thanks, B.J.
 
Please use Generic exception class i.e System.Exception. This is the superset
of all exception classes the u've mentioned.
 
You could try this:

try{..}
catch(Exception exc){
treatException(exc);
}

public void treatException(Exception exc){
SAME CODE IN ALL CATCH BLOCKS.
}

In case you want to write different code for FormatException or
OverflowException you can write that in treatException:

if(exc is FormatException){CUSTOM FormatException CODE}

or a better one:

switch(exc.GetType().ToString())
{
case "FormatException":
CUSTOM FormatException CODE
break;
}

Hope it helps,
 
Ravi said:
Please use Generic exception class i.e System.Exception. This is the superset
of all exception classes the u've mentioned.

It's also the superset of many other exceptions though. It's usually a
good idea to only catch specific exceptions unless you *really* want to
catch and handle/log every exception.
 
You can use double.TryParse() which returns a bool as an out parameter
saying wheather the parse succeeded or not, not exception will be thrown in
any case.

Currently it is not possible to catch multiple exceptions in one catch
block, this feature is called exception filtering and I hope that MS will
include it in one of the next versions of c#, currently it is only available
to vb programmers.
 
Back
Top