Catching the Uncaught Exceptions - Java Language Basics

Java examples for Language Basics:try catch finally

Introduction

Java can register an ExceptionHandler() either per thread or globally.

The following code demonstrates an example of registering an exception handler on a per-thread basis.

Demo Code

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
      System.out.println("Woa! there was an exception thrown somewhere! "
          + t.getName() + ": " + e);
    });/* www  .j  a  v  a  2 s  .  co  m*/

    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));
    }
  }
}

Result


Related Tutorials