Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch all types of exception in one single catch block?

catch(Exception ex)
{
    //do what you want here

    //When type of exception is System.Web.Services.Protocols.SoapException
    //if (ex.Code.Name.Equals("Client"))
    //{
    //      msg = "service's function not exist";
    //}
    //else if (ex.Code.Name.Equals("Server"))
    //{
    //     msg = "function error"
    //}
    //else
    //{
    //     msg = "unknown";
    //}
    //MessageBox.Show(msg, "error", MessageBoxButtons.OK);

**But ex is not System.Web.Services.Protocols.SoapException so I cannot call ex.Code.Name.Equals("Client")**


//When System.Net.WebException
//switch (ex.Status)
//{
//   case System.Net.WebExceptionStatus.ConnectFailure:
//              do some thing
                break;
//   case System.Net.WebExceptionStatus.Timeout:
                //do some thing
                break;
//    case System.Net.WebExceptionStatus.ProtocolError:
            switch (((System.Net.HttpWebResponse)ex.Response).StatusCode)
            {
                  case System.Net.HttpStatusCode.NotFound:
                        //do some thing
                        break;
                    case System.Net.HttpStatusCode.ServiceUnavailable:
                        //do some thing
                        break;
                    case System.Net.HttpStatusCode.Unauthorized:
                        //do some thing
                        break;
                    default:
                        //do some thing
                        break;
                }
                break;
            default:
                //do some thing
                break;
        }
}

But Exception is not System.Net.WebException. So cannot call ex.Status

My problem:

I have a Smartclient software include WindowsForm as client and a webservice as server. Client and Server both are n-tiers application I have tested and found that has any problem when call service from Client

  1. in app.config: service's path wrrong . I catch System.NotSupportedException
  2. Or when the server cannot connect: System.Net.WebExceptionStatus
  3. Server's webconfig is wrong : System.InvalidOperationException
  4. Service throws an exception: System.Web.Services.Protocols.SoapException ...

My Idea

I call the Exception that as representative of all other exception types is representativeAlException I have namespace : Common and two classese representativeAlException.cs and BusinessExceptionHandler.cs

Make a common function with a param as (representativeAlException ex)

            try
            {
                Err_LogCheck.Service1.Service1 service = new Err_LogCheck.Service1.Service1();
                return service.getDeviceByZero(ZERO);
            }
            catch (Common.representativeAlException ex)
            {
                Common.BusinessExceptionHandler.ProcessException(ex);
            }

What I want to do

Where the service is called. Only one catch block can handler for all type of Exception

in ProcessException(representativeAlException ex) function

switch (ex)
{
case System.InvalidOperationException:
 //Do some thing
 break;
case System.NotSupportedException:
 //Do some thing
 break;
case System.Web.Services.Protocols.SoapException:
 //do some thing
 break;
...
...
like image 569
user1299527 Avatar asked Nov 27 '22 21:11

user1299527


2 Answers

To handle all exception, use Exception class.

try
{

}
catch(Exception ex)
{
     switch (ex.GetType().ToString())
     {
         case "System.InvalidOperationException":
              //cast ex to specific type of exception to use it's properties
              ((InvalidOperationException)ex).SomeMethod();
         break;
         case "System.NotSupportedException":
             ((System.NotSupportedException)ex).AnotherMethod();
         break;
         case "System.Web.Services.Protocols.SoapException":
             ((System.Web.Services.Protocols.SoapException)ex).OtherMethod();
         break;
     }

}

Why can't you just use multiple catch block anyway?

like image 194
dpp Avatar answered Dec 15 '22 05:12

dpp


User2808350 is correct that try catch blocks can have many different catches for a reason, however sometimes you find you are repeating yourself (DRY) when using this pattern.

An alternative that can result in concise, readable code is to use the is operator which evaluates to true if your exception is an instance of a particular type or one that derives from that type. Unfortunately it's not possible to use the is operator in a switch block, so you have to use if-then-else.

Here is an example where I test the exception type and set the exit code accordingly.

try
{
    // try something
}
catch (Exception e)
{
    if (e is FileNotFoundException)
        Environment.ExitCode = 2;
    else if (e is InvalidOperationException)
        Environment.ExitCode = 1;
    else
        Environment.ExitCode = 42;
    throw;
}
like image 21
Onkel-j Avatar answered Dec 15 '22 07:12

Onkel-j