KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 3: Exception Handling

throw, throws, Exception Propagation, Built-in & Custom Exceptions

HIGH PRIORITY (Prep Guide)Official Syllabus~16 min study
Official KTU 2024 Syllabus Topics Covered Here
throw keywordthrows keywordException propagationJava built-in exceptionsCustom exceptionsCreating and using user-defined exceptions

1. Topic Introduction

So far, the JVM created and threw exceptions automatically (10 / 0). What if your own business logic detects a problem—such as an underage voter, an invalid negative withdrawal amount, or an empty balance—and wants to reject it cleanly? Java provides **throw (to throw an exception explicitly), throws (to delegate checked exceptions up the call chain), and Custom Exceptions** (extending Exception for domain-specific errors!).

2. Start From Zero: Pulling the Emergency Alarm (throw) vs Warning Sign on the Door (throws)

**throw** is an action inside a method: you literally construct an exception object and pull the emergency alarm (throw new InvalidAgeException("Under 18");). **throws** is a warning label written on the method's doorway (void register(int age) throws InvalidAgeException), telling callers: 'Warning! This room doesn't catch that alarm itself—anyone calling me must handle it or pass the warning onward!'

Key Takeaway: throw throws a single Throwable instance inside a method body; throws declares comma-separated exception types in a method header. Custom checked exceptions extend Exception.

3. Essential Exam Definitions

throw Keyword
Statement inside a method/block used to explicitly throw a single Throwable object (throw new MyException("msg"); or rethrowing a caught parameter throw e;).
throws Keyword
Clause appended to a method declaration (void readFile() throws IOException, SQLException) listing checked exceptions the method might throw without handling internally, pushing responsibility to the caller.
Exception Propagation
Mechanism where an unhandled exception automatically travels backward (unwinds) down the runtime call stack from callee to caller until a matching catch block is found (or the default JVM handler terminates the thread).
Custom (User-Defined) Exception
A programmer-defined class extending Exception (for a checked custom exception) or RuntimeException (for unchecked), usually overriding/calling super(message) or toString().

4. Detailed Technical Explanation & Syntax

1. Rules of throw & throws

For throw ThrowableInstance;: The thrown expression MUST be an instance of Throwable or its subclass—throwing int, String, or Object causes a compile error! Flow stops immediately after throw (no statements after throw in the same block execute).

For throws Ex1, Ex2: Mandatory for all Checked Exceptions thrown inside a method if not caught locally; optional for Error and RuntimeException.

2. Exception Propagation Across Methods

Suppose main() calls methodA(), which calls methodB(), which throws an exception. If methodB() has no catch, the JVM pops methodB's stack frame and searches methodA(); if methodA() lacks a match, it propagates up to main(). Note: Unchecked exceptions propagate automatically; checked exceptions propagate ONLY if every intermediate method declares throws!

3. Java Built-In Exceptions (java.lang) & Custom Exceptions

Built-in java.lang Unchecked Exceptions include ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NumberFormatException, IllegalArgumentException, ClassCastException. Built-in Checked Exceptions include ClassNotFoundException, InterruptedException, CloneNotSupportedException (plus java.io.IOException, java.sql.SQLException).

Creating a Custom Exception: Define class InsufficientFundsException extends Exception, supply a constructor calling super(message) (so getMessage() and toString() work cleanly), throw it inside business logic, and declare throws InsufficientFundsException on the method!

5. Working Principle: Lifecycle of a Custom Checked Exception

  1. 1. Define class InsufficientBalanceException extends Exception calling super(msg).
  2. 2. Method withdraw(double amt) throws InsufficientBalanceException checks if (amt > balance) throw new InsufficientBalanceException(...).
  3. 3. Caller wraps withdraw(...) in try { ... } catch (InsufficientBalanceException e) { ... }.

7. Complete Java Code Examples & Tracing

Custom Checked Exception (`throw` + `throws` + Propagation)CustomExceptionDemo.java
Creates a domain-specific checked exception InvalidMarksException, demonstrates propagation from validateMarks() -> processResult() -> main(), and handles it cleanly.
1// Step 1: User-defined checked exception extending Exception
2class InvalidMarksException extends Exception {
3 private final int invalidValue;
4
5 public InvalidMarksException(int invalidValue, String message) {
6 super(message); // Passes message to Throwable/Exception
7 this.invalidValue = invalidValue;
8 }
9
10 @Override
11 public String toString() {
12 return "InvalidMarksException[value=" + invalidValue + "]: " + getMessage();
13 }
14}
15
16public class CustomExceptionDemo {
17 // Step 2: Explicit 'throw' + 'throws' declaration
18 static void validateMarks(int marks) throws InvalidMarksException {
19 if (marks < 0 || marks > 60) {
20 throw new InvalidMarksException(marks, "KTU ESE marks must be between 0 and 60.");
21 }
22 System.out.println("Valid ESE Marks recorded: " + marks);
23 }
24
25 // Step 3: Exception propagation (delegates upward using 'throws')
26 static void processResult(int marks) throws InvalidMarksException {
27 validateMarks(marks); // Propagates upward if exception thrown
28 }
29
30 public static void main(String[] args) {
31 try {
32 processResult(48);
33 processResult(75); // Triggers custom exception!
34 } catch (InvalidMarksException e) {
35 System.out.println("Caught in main -> " + e);
36 }
37 }
38}
Expected Output
Valid ESE Marks recorded: 48
Caught in main -> InvalidMarksException[value=75]: KTU ESE marks must be between 0 and 60.
Keywords:throwthrowsextendsExceptionsupertrycatch
Common Exam & Coding Mistakes
  • Confusing throw (used inside method body with an object new Ex()) and throws (used in method signature with class names Ex1, Ex2).
  • Forgetting throws on validateMarks() when throwing a custom class that extends Exception.
  • Trying to throw "Error"; (a String is NOT a Throwable!).

Comparison Tables

throw vs throws (Top KTU 3/6-Mark Question!)
Criterionthrowthrows
PurposeExplicitly throws an exception objectDeclares exceptions a method may propagate to caller
LocationInside method or block bodyIn method signature/header
OperandFollowed by ONE Throwable instance (new Ex())Followed by 1 or more exception CLASS names (IOEx, SQLEx)
PropagationTransfers control immediately to nearest matching catchInforms compiler/caller to handle or re-declare checked exceptions
final vs finally (Quick Exam Clarification)
KeywordMeaning
finalModifier for constants (no reassign), methods (no override), and classes (no inheritance).
finallyCode block after try-catch guaranteeing cleanup execution regardless of exceptions.

Real-World Applications

  • Banking APIs throw custom InsufficientBalanceException; validation pipelines propagate errors cleanly back to API controllers.

Important KTU Exam Points

  • Always know the 4-row throw vs throws comparison table.
  • Writing a complete Custom Exception program (extends Exception + super(msg) + throw + throws + try-catch) is a classic 6-mark/9-mark question!

Memory Techniques & Revision

  • throw = Singular Action inside body (throw new ...;); throws = Plural Warning on method header (throws Ex1, Ex2).

Common Pitfalls to Avoid

  • Writing throws new MyException() on method header or throw MyException; inside method body.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

  • throw is used inside a method body followed by a single Throwable object (throw new ArithmeticException("bad");) to raise an exception explicitly.
  • throws is used in a method declaration followed by exception class names (void read() throws IOException) to warn callers of checked exceptions the method does not catch internally.

Quick Understanding Check

1. Which statement is syntactically CORRECT?