Java Notes
Complete guide to throw and throws keywords in Java — how to manually throw exceptions, declare checked exceptions, method signatures, exception propagation, and real-world patterns.
Overview
Java provides two keywords for working with exceptions proactively:
| Keyword | Purpose | Location | Used With |
|---|---|---|---|
throw | Actually throws an exception object | Inside method body | Exception instance |
throws | Declares that a method might throw exceptions | Method signature | Exception class names |
Think of it this way:
throw= "I'm throwing this ball NOW" (action)throws= "Warning: I might throw a ball" (declaration)
The throw Keyword
Syntax
throw new ExceptionType("error message");Basic Example
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
How throw Works Internally
| 1. Exception object created | |
|---|---|
| 2. Stack trace captured | |
| 3. Method exits immediately | |
| 4. Caller's catch is checked |
Throwing Different Exception Types
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| Error | Cannot divide by zero |
| Processing | Alice |
| Null error | Name cannot be null |
| Invalid | Name cannot be empty |
| Processing | Bob |
Re-throwing an Exception
Sometimes you want to catch an exception, do something (like logging), and then re-throw it:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
Wrapping Exceptions (Exception Chaining)
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
The throws Keyword
Syntax
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
// method body
}Why throws is Needed
The throws keyword is required when a method can throw a checked exception that it doesn't handle internally. It tells the compiler (and the caller) that this method might throw this exception.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
Multiple Exceptions in throws
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
Exception Propagation with throws
When a method declares throws, the exception propagates UP the call stack:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| Main | Calling level1() |
| Level 1 | Calling level2() |
| Level 2 | Calling level3() |
| Level 3 | Throwing IOException |
| Main | Caught exception! |
| Main | Disk full |
| Main | Program continues |
Propagation Diagram:
throw vs throws — Complete Comparison
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| Processing | report.txt |
| Invalid arg | Filename is null |
| IO problem | Filename is empty |
| Processing | data.csv |
#
Q8: Can you throw checked exceptions without declaring them?
A: No. If a method throws a checked exception, it MUST either (1) catch it within the method, or (2) declare it in the method signature with throws. Unchecked exceptions (RuntimeException subclasses) do NOT require declaration. Violating this rule causes a compile error.
Q9: What is exception wrapping (chaining)?
A: Catching a low-level exception and throwing a new higher-level exception with the original as the cause: catch (SQLException e) { throw new DataAccessException("Query failed", e); }. This preserves the root cause (accessible via getCause()) while providing context-appropriate abstraction.
Q10: Can a constructor throw exceptions?
A: Yes! Constructors can throw both checked and unchecked exceptions. If a constructor throws, the object is NOT created (new returns nothing, partial construction is garbage collected). Checked exceptions in constructors must be declared with throws just like methods.
Q11: What is the difference between "throw" and "throws" in method overriding?
A: Overriding methods can throw: (1) same exceptions as parent, (2) subclass exceptions (narrower), (3) fewer exceptions, or (4) no exceptions. They CANNOT throw broader checked exceptions or new checked exceptions not declared by the parent. Unchecked exceptions have no restrictions in overriding.
Q12: What happens if you throw an exception inside a catch block?
A: The exception propagates normally to the next enclosing try-catch or up the call stack. The finally block (if any) still executes before the exception leaves the method. This is commonly done for exception chaining or re-throwing after logging.
Summary Table
| Feature | throw | throws |
|---|---|---|
| What it does | Throws an exception object | Declares possible exceptions |
| Where used | Inside method body | In method signature |
| Followed by | Exception instance (new Exception()) | Exception class names |
| Count | One exception at a time | Multiple (comma-separated) |
| Required for | Both checked and unchecked | Only checked exceptions |
| Example | throw new IOException("msg") | void m() throws IOException |
When to Use throw vs throws
Use throw when:
- Input validation fails
- Business rules are violated
- You need to convert one exception type to another
- You want to re-throw a caught exception
Use throws when:
- Your method calls another method that throws a checked exception
- Your method intentionally throws a checked exception
- You want the caller to decide how to handle the error
Real-World Example: User Registration System
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| ✓ User registered | Alice Johnson (alice@example.com) |
| ✗ Registration failed | Name cannot be empty |
| ✗ Registration failed | Invalid email format: invalid-email |
| ✗ Registration failed | Email already registered: admin@company.com |
| ✗ Registration failed | Must be at least 13 years old. Got: 10 |
| ✓ User registered | Frank Wilson (frank@test.com) |
Throws with Method Overriding Rules
When overriding methods, there are strict rules about throws:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Rules Summary:
- Child can throw the same exception as parent
- Child can throw a subclass (narrower) exception
- Child can choose not to throw any exception
- Child CANNOT throw a broader or new checked exception
Common Mistakes
1. Using throw with a class instead of an object
// ❌ WRONG: throw expects an object, not a class
throw IOException;
// ✅ CORRECT: Create an instance
throw new IOException("Error message");2. Code after throw statement
// ❌ WRONG: Unreachable code
void method() {
throw new RuntimeException("error");
System.out.println("hello"); // Compile error: unreachable
}3. Declaring unchecked exceptions in throws (unnecessary)
// Not wrong, but unnecessary and misleading
void method() throws NullPointerException, ArithmeticException {
// Unchecked exceptions don't need throws declaration
}
// ✅ Better: Just document them in Javadoc
/**
* @throws NullPointerException if input is null
*/
void method() {
// ...
}4. Declaring throws Exception everywhere
// ❌ BAD: Too broad, forces callers to catch Exception
void doStuff() throws Exception { }
// ✅ GOOD: Be specific
void doStuff() throws IOException, SQLException { }Interview Questions
Q1: What is the difference between throw and throws?
Answer: throw is used inside a method body to actually throw an exception object. throws is used in the method declaration to indicate which checked exceptions the method might throw. throw is followed by an exception instance; throws is followed by exception class names.
Q2: Can we throw unchecked exceptions without declaring throws?
Answer: Yes. Unchecked exceptions (subclasses of RuntimeException) do not require a throws declaration. You can throw new RuntimeException() from any method without declaring it.
Q3: Can a method throw an exception that is NOT declared in its throws clause?
Answer: Only unchecked exceptions. If a method throws a checked exception, it MUST be declared in the throws clause. If not, you get a compilation error.
Q4: What happens if main() uses throws?
Answer: The exception propagates to the JVM, which handles it via the default exception handler (prints stack trace and terminates). Example: public static void main(String[] args) throws IOException { ... }
Q5: Can we re-throw a caught exception?
Answer: Yes. Inside a catch block, you can use throw e; to re-throw the same exception, or throw new AnotherException("msg", e); to wrap it in a different exception (exception chaining).
Q6: How does throws work with method overriding?
Answer: The overriding method can throw the same exception, a subclass exception, or no exception at all. It CANNOT throw a broader checked exception or a new checked exception not declared by the parent method.
Continue the lesson path