Concept Flow - Throw keyword
Start
Check condition
Yes|No
Throw Exception
Exception Propagates
Catch or Program Ends
The program checks a condition, and if true, it throws an exception which propagates until caught or program ends.
Jump into concepts and practice - no test required
public class Test { public static void main(String[] args) { int age = 15; if (age < 18) { throw new IllegalArgumentException("Age must be 18 or older"); } } }
| Step | Action | Condition | Result | Exception Thrown |
|---|---|---|---|---|
| 1 | Set age = 15 | - | age = 15 | No |
| 2 | Check if age < 18 | 15 < 18 | True | No |
| 3 | Throw IllegalArgumentException | - | - | Yes: "Age must be 18 or older" |
| 4 | Program stops or exception propagates | - | - | Exception propagates |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| age | undefined | 15 | 15 | 15 |
Throw keyword in Java:
- Used to throw an exception explicitly
- Syntax: throw new ExceptionType("message");
- Stops normal flow and propagates exception
- Usually inside condition checks
- Must be caught or declared to avoid program crashWhat does the throw keyword do in Java?
throwthrow keyword is used to send an exception object explicitly when an error happens.throw does not catch exceptions (that's catch), nor declare exceptions (that's throws), nor create threads.throw sends exception = B [OK]Which of the following is the correct way to throw a new IllegalArgumentException in Java?
?
throw new ExceptionType("message") with parentheses and semicolon.new, parentheses, and semicolon. Options B and D miss parentheses or new. throws new IllegalArgumentException("Invalid argument"); uses throws which is for method declarations, not throwing.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());
}
}
}RuntimeException with message "Error happened".e.getMessage(), which is "Error happened".Identify the error in the following code snippet:
public class Example {
public static void main(String[] args) {
throw new Exception("Problem");
}
}Exception, which is a checked exception in Java.throws in the method signature. This code does neither, causing a compile error.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?
IllegalArgumentException, which is an unchecked exception.IllegalArgumentException.checkNumber inside a try-catch block catching IllegalArgumentException. -> Option D