import java.util.Scanner; import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; /** Demo exceptions. @author Jed Yang, 2018-01-15 */ public class ExceptionDemo { /** This method might throw an exception if denominator is 0, because dividing by 0 is bad for the universe. */ public static int ratio(int numerator, int denominator) { //* if (denominator == 0) { System.err.println("Should not divide by 0. Bye!"); // System.exit(2); throw new RuntimeException("Eh, the universe just exploded."); } //*/ return numerator/denominator; /* try { } catch (ArithmeticException e) { System.err.println("Something went wrong."); return -1; } //*/ } public static void main(String[] args) { int top = 0; int bottom = 0; Scanner kb = new Scanner(System.in); try { System.out.print("Integer, please: "); top = kb.nextInt(); System.out.print("Positive integer, please: "); bottom = kb.nextInt(); //* } catch (java.util.InputMismatchException e) { System.err.println("Please type an integer next time. Bye!"); System.exit(1); } //*/ //* try { System.out.println("The ratio is: " + ratio(top, bottom)); } catch (ArithmeticException e) { System.err.println("I caught the exception outside!"); } //* catch (RuntimeException e) { System.err.println("I am catching the exception I threw, with message: " + e.getMessage()); } //*/ // readFromFile(); } /** Removing the try-catch block will require adding 'throws FileNotFoundException' to the method declaration. */ public static void readFromFile() throws FileNotFoundException { String inputFilePath = "somelines.txt"; File inputFile = new File(inputFilePath); Scanner scanner = null; scanner = new Scanner(inputFile); /* try { } catch (FileNotFoundException e) { System.err.println(e); System.exit(1); } */ } }