2

Below is the code I have developed for a thread.

   int i;
    Thread thread = new Thread()
    {
        @Override
        public void run() {
            try {
                while(true) {
                    sleep(10000);
                    i++
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();

Is there any possible way I can use any other catch or exception to catch all possible crushes within it? Thank you in advance!

zETO
  • 191
  • 7

2 Answers2

2

Just have catch (Exception ex) as well as catch (InterruptedException e)

Tim B
  • 40,716
  • 16
  • 83
  • 128
2

It seems that only exception that block can throw,you have already handled but for safer side you can catch parent exception too i,e (Exception e) as below :

 try {
   //stuff
}
catch (InterruptedException e) {
     e.printStackTrace();
}
catch (Exception e) {
      e.printStackTrace();
}
Kick
  • 4,823
  • 3
  • 22
  • 29
  • Thanks for your answer, although I'll accept the first one because he said it first. – zETO Feb 02 '14 at 20:26
  • thnks @We'reAllMadHere :) – Kick Feb 02 '14 at 20:31
  • In general, capturing Exception is a **bad practice**, more info on this here http://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception – nKn Feb 02 '14 at 20:34
  • @NKN yes i knw.but it will better to dnt leave any exception without any catch.You can add the exception catch after specific exception like in this case we are handling InterruptedException which can be caused by sleep but if other exception arise thn super class exception will handle – Kick Feb 02 '14 at 20:38