chris-piekarski
1/3/2014 - 10:37 PM

How does Java try/catch/finally work?

How does Java try/catch/finally work?


package com.cpiekarski.helloworld;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

/**
 * javac -d . HelloWorldApp.java
 * java -cp . com.cpiekarski.helloworld.HelloWorldApp
 */
public class HelloWorldApp {
    public static void finallyWithException() {
        try {
            int x = 10 / 0;
        } catch (Exception e) {
            System.out.println(e.toString());
            return;
        } finally {
            System.out.println("Goodbye finallyWithException");
        }
    }

    public static void finallyWithReturn() {
        try {
            System.out.println("Hello World!"); // Display the string.
            return;
        } catch (Exception e) {

        } finally {
            System.out.println("Goodbye finallyWithReturn");
        }
    }

    public String getInput(String prompt) throws IOException {
        System.out.println(prompt);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String text = in.readLine();
        return text;
    }

    public static void main(String[] args) {
        System.out.println(args.length);
        finallyWithReturn();
        finallyWithException();
        
        HelloWorldApp x = new HelloWorldApp();
        try {
            String color = x.getInput("What is your favorite color:");
            System.out.println("App got: "+color);
        } catch (IOException e) {
                
        }
    }
}