throw, throws, Exception Propagation, Built-in & Custom 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!).
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!'
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 KeywordThrowable object (throw new MyException("msg"); or rethrowing a caught parameter throw e;).throws Keywordvoid readFile() throws IOException, SQLException) listing checked exceptions the method might throw without handling internally, pushing responsibility to the caller.catch block is found (or the default JVM handler terminates the thread).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. Define
class InsufficientBalanceException extends Exceptioncallingsuper(msg). - 2. Method
withdraw(double amt) throws InsufficientBalanceExceptionchecksif (amt > balance) throw new InsufficientBalanceException(...). - 3. Caller wraps
withdraw(...)intry { ... } catch (InsufficientBalanceException e) { ... }.
7. Complete Java Code Examples & Tracing
InvalidMarksException, demonstrates propagation from validateMarks() -> processResult() -> main(), and handles it cleanly.| 1 | // Step 1: User-defined checked exception extending Exception |
| 2 | class 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 | |
| 16 | public 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 | } |
Valid ESE Marks recorded: 48 Caught in main -> InvalidMarksException[value=75]: KTU ESE marks must be between 0 and 60.
throwthrowsextendsExceptionsupertrycatch- Confusing
throw(used inside method body with an objectnew Ex()) andthrows(used in method signature with class namesEx1, Ex2). - Forgetting
throwsonvalidateMarks()when throwing a custom class that extendsException. - Trying to
throw "Error";(aStringis NOT aThrowable!).
Comparison Tables
throw vs throws (Top KTU 3/6-Mark Question!)| Criterion | throw | throws |
|---|---|---|
| Purpose | Explicitly throws an exception object | Declares exceptions a method may propagate to caller |
| Location | Inside method or block body | In method signature/header |
| Operand | Followed by ONE Throwable instance (new Ex()) | Followed by 1 or more exception CLASS names (IOEx, SQLEx) |
| Propagation | Transfers control immediately to nearest matching catch | Informs compiler/caller to handle or re-declare checked exceptions |
final vs finally (Quick Exam Clarification)| Keyword | Meaning |
|---|---|
final | Modifier for constants (no reassign), methods (no override), and classes (no inheritance). |
finally | Code 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
throwvsthrowscomparison 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 orthrow 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.
throwis used inside a method body followed by a singleThrowableobject (throw new ArithmeticException("bad");) to raise an exception explicitly.throwsis 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?