⬅ Previous Topic
Java try-with-resourcesNext Topic ⮕
Java throws Keyword⬅ Previous Topic
Java try-with-resourcesNext Topic ⮕
Java throws Keywordthrow
Keyword in JavaIn Java, exceptions can be thrown automatically by the JVM or manually by the programmer. The throw
keyword allows developers to deliberately trigger an exception. Why? Sometimes, you want to fail fast or validate input before continuing further. That's where throw
shines.
throw
in JavaThe throw
statement is used followed by an instance of an exception class:
throw new ExceptionType("Error message");
Let’s say you're writing a function that shouldn’t accept a negative age. Instead of letting the program crash somewhere down the line, you raise a red flag immediately.
public class Main {
static void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
System.out.println("Age is valid: " + age);
}
public static void main(String[] args) {
validateAge(-5);
System.out.println("End of program");
}
}
Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative
at Main.validateAge(Main.java:4)
at Main.main(Main.java:9)
We manually threw an IllegalArgumentException
when the age was invalid. As soon as it was thrown, the normal flow stopped, and the program exited before reaching the final print statement.
throw
with Custom ExceptionsSometimes, built-in exceptions aren't descriptive enough. You can create your own custom exceptions and throw them using the same throw
keyword.
// Define a custom exception
class LowBalanceException extends Exception {
public LowBalanceException(String message) {
super(message);
}
}
public class Bank {
static void withdraw(int amount) throws LowBalanceException {
if (amount > 1000) {
throw new LowBalanceException("Withdrawal amount exceeds limit");
}
System.out.println("Withdrawn: " + amount);
}
public static void main(String[] args) throws LowBalanceException {
withdraw(1500);
}
}
Exception in thread "main" LowBalanceException: Withdrawal amount exceeds limit
at Bank.withdraw(Bank.java:9)
at Bank.main(Bank.java:14)
throw
Worksnew
.catch
block or crashes the program if uncaught.Throwable
— which includes Exception
and Error
.throw
Use it to:
throw IOException;
instead of throw new IOException();
)throws
in the method signature if the exception is checkedThrowable
objects (like String
or int
)Think of throw
as pulling the fire alarm in a building. You're not solving the problem (that’s for try-catch
to handle), but you're raising the alert that something went wrong and needs attention. Immediate action is taken — either someone catches it or the whole system shuts down.
⬅ Previous Topic
Java try-with-resourcesNext Topic ⮕
Java throws KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.