Java Exception catch uncaught exception

Description

Java Exception catch uncaught exception


import java.util.Random;

public class Main {
   public static void main(String[] args) {
      start();/*from   w w w  .  j  ava2s  . co  m*/
      startForCurrentThread();
   }

   private static void start() {
      Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
         @Override
         public void uncaughtException(Thread t, Throwable e) {
            System.out.println("Woa! there was an exception thrown somewhere! " + t.getName() + ": " + e);
         }
      });

      final Random random = new Random();
      for (int j = 0; j < 10; j++) {
         int divisor = random.nextInt(4);
         System.out.println("200 / " + divisor + " Is " + (200 / divisor));
      }
   }

   private static void startForCurrentThread() {
      Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
         @Override
         public void uncaughtException(Thread t, Throwable e) {
            System.out.println("In this thread " + t.getName() + " an exception was thrown " + e);
         }
      });

      Thread someThread = new Thread(new Runnable() {
         @Override
         public void run() {
            System.out.println(200 / 0);
         }
      });
      someThread.setName("Some Unlucky Thread");
      someThread.start();

      System.out.println("In the main thread " + (200 / 0));
   }
}



PreviousNext

Related