Catching Exceptions - Java Language Basics

Java examples for Language Basics:try catch finally

Introduction

Use the built-in try/catch statement to catch exceptions.

try { 
  // code here 
} catch (NumberFormatException|NullPointerException ex) { 
  // logging 

} 

Demo Code


public class Main {
  public static void main(String[] args) {
    System.out.println(m("1234"));
    System.out.println(m("12345"));
    System.out.println(m("123456"));
    System.out.println(m(null));//from   www. j  a v  a 2  s. c  o  m
  }

  private static boolean m(String aString) {
    try {
      return aString.length() > 5;
    } catch (NullPointerException e) {
      System.out.println("An Exception Occurred!");
      return false;
    }
  }
}

Result


Related Tutorials