The throw keyword is used to send an error or exception when something goes wrong in your program. It helps you stop the normal flow and handle problems clearly.
Throw keyword in Java
Start learning this pattern below
Jump into concepts and practice - no test required
throw new ExceptionType("Error message");
You must create a new exception object with new before throwing it.
The throw keyword only sends one exception at a time.
throw new IllegalArgumentException("Invalid age");
throw new NullPointerException("Object is null");
throw new RuntimeException("Something went wrong");
This program checks if a number is positive. If the number is negative, it throws an exception with a message. Otherwise, it prints the number.
public class ThrowExample { public static void checkNumber(int number) { if (number < 0) { throw new IllegalArgumentException("Number must be positive"); } else { System.out.println("Number is " + number); } } public static void main(String[] args) { checkNumber(10); checkNumber(-5); } }
When you use throw, the program stops running the current method unless the exception is caught.
You can only throw objects that are subclasses of Throwable, like Exception or Error.
Use throw to create clear and meaningful error messages for easier debugging.
throw sends an exception to stop normal program flow when an error happens.
You create a new exception object and use throw to send it.
It helps make your program safer by handling problems clearly.
Practice
What does the throw keyword do in Java?
Solution
Step 1: Understand the role of
Thethrowthrowkeyword is used to send an exception object explicitly when an error happens.Step 2: Differentiate from other keywords
throwdoes not catch exceptions (that'scatch), nor declare exceptions (that'sthrows), nor create threads.Final Answer:
It sends an exception to stop normal program flow when an error occurs. -> Option BQuick Check:
throwsends exception = B [OK]
- Confusing throw with throws keyword
- Thinking throw catches exceptions
- Mixing throw with thread creation
Which of the following is the correct way to throw a new IllegalArgumentException in Java?
?
Solution
Step 1: Check syntax for throwing exceptions
To throw an exception, usethrow new ExceptionType("message")with parentheses and semicolon.Step 2: Identify correct option
throw new IllegalArgumentException("Invalid argument"); uses correct syntax withnew, parentheses, and semicolon. Options B and D miss parentheses ornew. throws new IllegalArgumentException("Invalid argument"); usesthrowswhich is for method declarations, not throwing.Final Answer:
throw new IllegalArgumentException("Invalid argument"); -> Option CQuick Check:
throw + new + parentheses = A [OK]
- Omitting 'new' keyword
- Using 'throws' instead of 'throw'
- Missing parentheses after exception class
What will be the output of the following Java code?
public class TestThrow {
public static void main(String[] args) {
try {
throw new RuntimeException("Error happened");
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}Solution
Step 1: Analyze the try block
The code throws a newRuntimeExceptionwith message "Error happened".Step 2: Analyze the catch block
The catch block catches the exception and prints its message usinge.getMessage(), which is "Error happened".Final Answer:
Error happened -> Option AQuick Check:
Exception message printed = C [OK]
- Expecting exception type name instead of message
- Thinking code causes compilation error
- Assuming no output without catch
Identify the error in the following code snippet:
public class Example {
public static void main(String[] args) {
throw new Exception("Problem");
}
}Solution
Step 1: Identify exception type
The code throwsException, which is a checked exception in Java.Step 2: Check handling of checked exceptions
Checked exceptions must be either caught in a try-catch block or declared withthrowsin the method signature. This code does neither, causing a compile error.Final Answer:
Missing try-catch block or throws declaration for checked exception. -> Option AQuick Check:
Checked exceptions need handling = D [OK]
- Ignoring checked exception rules
- Thinking main cannot throw exceptions
- Confusing checked and unchecked exceptions
Consider this method that throws an exception if the input is negative:
public void checkNumber(int num) {
if (num < 0) {
throw new IllegalArgumentException("Negative number not allowed");
}
System.out.println("Number is " + num);
}How should you call this method safely in your code?
Solution
Step 1: Identify exception type thrown
The method throwsIllegalArgumentException, which is an unchecked exception.Step 2: Decide safe calling practice
Although unchecked exceptions do not require declaration, to handle errors safely, call the method inside a try-catch block catchingIllegalArgumentException.Final Answer:
CallcheckNumberinside a try-catch block catchingIllegalArgumentException. -> Option DQuick Check:
Catch unchecked exceptions to handle errors safely = A [OK]
- Thinking unchecked exceptions must be declared
- Not catching exceptions leading to crashes
- Misusing throw keyword when calling methods
