-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
  • 13,420
  • 39
  • 101
  • 157

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
  • 9,349
  • 6
  • 55
  • 75
1
Try
{
} catch ( Exception e )
{
// catch all
}
Sievajet
  • 3,349
  • 2
  • 17
  • 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,074
  • 3
  • 14
  • 31