Skip to content

Instantly share code, notes, and snippets.

@chris-piekarski
Last active January 2, 2016 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-piekarski/8248035 to your computer and use it in GitHub Desktop.
Save chris-piekarski/8248035 to your computer and use it in GitHub Desktop.
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) {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment