-3

I have so many catch blocks after every try to catch different type of exception occurring under it.

Is there a way I can handle all these exception in one block instead of adding a new block for every exception?

... } catch (UnknownHostException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } catch (NullPointerException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } catch (ClientProtocolException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } catch (IllegalArgumentException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } catch (URISyntaxException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } catch (IOException e) {
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
        } finally{…}
Maven
  • 14,587
  • 42
  • 113
  • 174

3 Answers3

1

This is possible since Java 7

try { 
 ...
} catch( UnknownHostException | NullPointerException | ClientProtocolException ex ) { 
            Log.e(LOG_TAG_EXCEPTION, e.getMessage());
}

But you can use

try{
}
  catch (Exception e) { 
                Log.e(LOG_TAG_EXCEPTION, e.getMessage());
} 

More information http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

Saeed Masoumi
  • 8,746
  • 7
  • 57
  • 76
1
Try
{
} catch ( Exception e )
{
// catch all
}
Sievajet
  • 3,443
  • 2
  • 18
  • 22
0

If you're just logging the exception

catch (Exception e) { Log.e(LOG_TAG_EXCEPTION, e.getMessage()); }

is quite good enough. But if you want to react to a certain exception, you have to catch specific exceptions, like you did before.

Kody
  • 1,154
  • 3
  • 14
  • 31