Last active
January 2, 2016 03:59
-
-
Save chris-piekarski/8248035 to your computer and use it in GitHub Desktop.
How does Java try/catch/finally work?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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