Lesson Completion
Back to course

throw and throws: Creating and Declaring Exceptions

Intermediate
15 minutesβ˜…4.8Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: throw is used to explicitly throw an exception object. throws is used in method signatures to declare that a method might throw certain exceptions. throw actually throws; throws just warns callers.

Think of smoke alarms:

  • throw: Pulling the fire alarm (actually triggering the alarm)
  • throws: Sign saying "Fire alarm installed" (warning it might go off)

2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy: The Package Delivery

  • throw: The delivery person throws the package over your fence
  • throws: Shipping label warns "Fragileβ€”may break in transit"

3. Technical Mastery (The "Deep Dive")

Syntax

java
// throw: Inside method body throw new ExceptionType("message"); // throws: In method signature void methodName() throws ExceptionType { // might throw exception }

Key Differences

Featurethrowthrows
LocationInside method bodyMethod signature
PurposeActually throw exceptionDeclare possible exceptions
CountOne exception at a timeMultiple (comma-separated)
Examplethrow new IOException()void read() throws IOException

4. Interactive & Applied Code

java
public class ThrowThrowsDemo { public static void main(String[] args) { // Example 1: throw try { validateAge(15); } catch (IllegalArgumentException e) { System.out.println("❌ " + e.getMessage()); } // Example 2: throws (must handle or declare) try { readFile("data.txt"); } catch (java.io.IOException e) { System.out.println("❌ " + e.getMessage()); } } // Using throw static void validateAge(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be 18+"); // βœ… throw } System.out.println("βœ… Valid age"); } // Using throws (declares exception) static void readFile(String filename) throws java.io.IOException { if (!filename.endsWith(".txt")) { throw new java.io.IOException("Invalid file type"); // throw inside } System.out.println("Reading file..."); } // Rethrowing exceptions static void processData() throws Exception { try { // Some operation throw new java.io.IOException("IO error"); } catch (java.io.IOException e) { System.out.println("Logging error..."); throw e; // Rethrow to caller } } }

5. The Comparison & Decision Layer

Decision Tree: throw vs throws

graph TD A{What do you need?} A -- Create and trigger exception --> B[Use throw] A -- Warn callers about exceptions --> C[Use throws] B --> D[throw new Exception] C --> E[void method throws Exception]

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "Can you override a method and throw a broader exception?" Answer: NO! Overriding methods can:

  • βœ… Throw fewer exceptions
  • βœ… Throw subclass exceptions
  • ❌ NOT throw broader exceptions
java
class Parent { void method() throws IOException { } } class Child extends Parent { void method() throws FileNotFoundException { } // βœ… OK (subclass) // void method() throws Exception { } // ❌ ERROR (broader!) }

Pro-Tip: Use throw for validation:

java
public void setAge(int age) { if (age < 0) throw new IllegalArgumentException("Negative age"); this.age = age; }

Fail fast! Don't wait for bugs to propagate.

Topics Covered

Java FundamentalsError Handling

Tags

#java#exceptions#try-catch#error-handling#robust-code

Last Updated

2025-02-01