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. ...

August 21, 2026 · 2 min · Vishwakant Mishra

Chapter 1 Intro

Exception Handling Checked and Unchecked Exceptions Checked - code calls a method that throws a checked exception, code detects an error and throws a checked exception Unchecked - code error like IndexOutOfBoundsException, internal error in JVM or runtime Checked exceptions must be specified with method declaration. Overriding function in the overloading class cannot have more checked exceptions or different checked exceptions than the overridden method in the base class. It can have no checked exceptions (even if the overridden method has exceptions). Finally try { return Integer.parseInt(s); } finally { return 0; } Beware of returns with try-finally. In the above code, if the try block doesn’t throw an error, finally will swallow the return and 0 will be returned instead of the parsed value. If try throws an error, finally will swallow the exception and the caller method will not receive an exception. Finally is supposed to handle cleanup. Don’t put code that changes the control flow. ...

August 19, 2026 · 2 min · Vishwakant Mishra