Try and Catch

Data Types and Exceptions in Java

Jim White

Java Developer

Problems in Java

  • Problems or issues can occur in applications
    • Due to wrong input
    • Due to coding errors
    • Due to unforeseen circumstances
  • Problems or issues are called exceptions
    • Interrupt the normal control flow
  • Java throws exceptions
Data Types and Exceptions in Java

Exception Example

public static void main(String[] args) {
    ArrayList<String> allStars = new ArrayList<String>();
    allStars.add("Mays");
    allStars.add("Aaron");
    allStars.add("Ruth");
    String last = allStars.get(3); // This will cause an exception
    System.out.println(last);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of 
bounds for length 3
Data Types and Exceptions in Java

Try

  • Wrap exception-generating code with a try-block
    • "Try this code and if there is a problem pass it to the catch block"
try {
    // Statements to be executed and watched for exceptions
}
Data Types and Exceptions in Java

Catch

  • Place a catch-block after the try
    • Acts as a handler to address exception problems
    • The exception caught is passed into this block as a parameter
  • try/catch blocks are required for some types exceptions
    • Optional for others
try {
    // Statements to be executed and watched for exceptions
} catch (Exception variable) {
    // Statements to execute if an exception has occurred
}
Data Types and Exceptions in Java

Catching IndexOutOfBoundsException

try {
  ArrayList<String> allStars = new ArrayList<String>();
  allStars.add("Mays");
  allStars.add("Aaron");
  allStars.add("Ruth");
  String last = allStars.get(3); // Accessing an element that isn't there
  System.out.println(last);
} catch (IndexOutOfBoundsException e) {
  System.out.println("Oops - wrong index");
}
Oops - wrong index
Data Types and Exceptions in Java

Multiple Catch

  • Use multiple catch blocks to handle different types of exceptions
  • Each catch gets its own exception type and exception variable
  • When exception occurs, Java checks the catch blocks in order until it finds a match
try {
    ArrayList<String> nums 
      = new ArrayList<String>();
    nums.add("one");
    String last = nums.get(0);
    Integer.valueOf(last);
    System.out.println(last);
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println(
      "Oops - String not a number");
}
Oops - String not a number
Data Types and Exceptions in Java

Catch "All"

  • Use catch (Exception variable){ } as a catch all
    • Handles any exception not handled by the other catch blocks
try {
    // Code to try
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops - String not a number");
} catch (Exception e) { // Handles all exceptions except the two above
    System.out.println("Something unplanned happened");
}
Data Types and Exceptions in Java

Finally

  • Code in finally block always executes
// When exception happens
try {
    Integer.valueOf("one");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Oops
Doing cleanup

 

// When no exception gets thrown
try {
    Integer.valueOf("1");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Doing cleanup
Data Types and Exceptions in Java

Exception object

  • The Exception object passed into the catch block is rich with information
  • Use methods on the object to learn more about what went wrong
    • .getMessage() to get the human readable cause
    • .getClass() to get the Exception class or type name
    • .printStackTrace() to display the stack trace (next slide)
public class ExceptionExample {

    public static void main(String[] args) {
        try {
            Integer.valueOf("one");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
Data Types and Exceptions in Java

Exception stack trace

  • The stack trace provides a record of the execution flow to the problem
    • Below: output from the previous code example - including the printed stack trace
For input string: "one"
java.lang.NumberFormatException: For input string: "one"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:661)
    at java.base/java.lang.Integer.valueOf(Integer.java:988)
    at foo/exceptions.ExceptionExample.main(ExceptionExample.java:7)
Data Types and Exceptions in Java

Let's practice!

Data Types and Exceptions in Java

Preparing Video For Download...