Chapter 2 Exceptions
Java Exceptions Checked/Unchecked Check out this example code. (Ignore two classes in same file for now) import java.util.Scanner; public class Calculator { int a; void setNum(String s) throws NumberFormatException { a = Integer.parseInt(s); } public int getNum() { return a; } } public class Main { public static void main(String[] args) { Calculator calculator = new Calculator(); Scanner scanner = new Scanner(System.in); try { calculator.setNum(scanner.next()); int a = calculator.getNum(); int b = Integer.parseInt(scanner.next()); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println("Error. Cannot divide by 0."); } catch (NumberFormatException e) { System.out.println("Please enter valid integers only."); } finally { System.out.println("End of program"); scanner.close(); } } } There are two types of exceptions in Java. ...