throw and throws
22 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)With throw, your own code can throw an exception when a value is wrong, such as a negative age or a withdrawal above the balance. The caller can then catch it like any other exception.
throw: report a bad value
throw is used to explicitly throw a single exception. Without a check, withdraw(3000, 4000) quietly returns a balance of -1000. Instead, throw an exception: the method stops at that line, and the caller learns that something went wrong.
Example 1 · ATM: amount more than balance
public class Atm { static int withdraw(int balance, int amount) { if (amount > balance) { throw new IllegalArgumentException("Not enough balance"); } return balance - amount; }
public static void main(String[] args) { try { System.out.println("Balance: " + withdraw(5000, 2000)); System.out.println("Balance: " + withdraw(3000, 4000)); } catch (IllegalArgumentException e) { System.out.println("Failed: " + e.getMessage()); } }}Balance: 3000 Failed: Not enough balance
What this code does
new IllegalArgumentException("Not enough balance")makes the exception, and the text becomes its message.IllegalArgumentExceptionis the usual type for "this value is not allowed".- For ₹4000,
throwstopswithdrawat once, soreturn balance - amountnever runs. maincatches it like any other exception, andgetMessage()gives back the text.
If nobody catches it
An exception you throw works exactly like one Java throws. If no caller catches it, the program stops with a stack trace, and your own message is in it.
Example 2 · Nobody catches it
public class AgeCheck { static void checkAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative: " + age); } System.out.println("Age OK: " + age); }
public static void main(String[] args) { checkAge(19); checkAge(-5); }}Age OK: 19 Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative: -5 at AgeCheck.checkAge(AgeCheck.java:4) at AgeCheck.main(AgeCheck.java:11)
What this code does
- Your own message is the message in the stack trace, so the report explains itself.
- The
throwis on line 4, andmaincalled the method on line 11.
The exception family
Every problem Java can throw belongs to one family under Throwable, split into two groups: Error and Exception. Every exception in this module so far is a RuntimeException, one kind of Exception.
An Error is a serious problem inside Java itself, like StackOverflowError from a method that calls itself forever (see Recursion basics (opens in a new tab)) or OutOfMemoryError. Programs do not catch these.
The exceptions Java already gives you, like ArithmeticException, NullPointerException and IllegalArgumentException, are called built-in exceptions. Exception classes you write yourself, like InsufficientBalanceException, are called user-defined (or custom) exceptions. Making one needs extends, so you will write your own in Your own exception classes (opens in a new tab); for now, throw the built-in ones.
Checked exceptions and throws
Some exceptions, like FileNotFoundException for a missing file, are checked: javac makes you catch them or declare them. The throws keyword is used in a method declaration to indicate that the method may throw one or more exceptions.
Example 3 · throws for a checked exception
public class PinCheck { static void checkPin(int pin) throws Exception { if (pin != 4321) { throw new Exception("Wrong PIN"); } System.out.println("PIN accepted"); }
public static void main(String[] args) { try { checkPin(4321); checkPin(1111); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }}PIN accepted Error: Wrong PIN
What this code does
Exceptionitself is checked, socheckPinmust saythrows Exceptionin its first line.- Because of
throws, every caller must handle it. Without the try-catch inmain,javacstops withunreported exception Exception; must be caught or declared to be thrown.
Unchecked exceptions are RuntimeException and its kinds: every exception you met before this lesson. They come from wrong values, so Java does not force you to catch or declare them. In short: throw (inside the method body) throws one exception now; throws (in the method's declaration) only warns that one or more may come.
Classify
Checked, unchecked or Error?
Tap a type, then tap its group.
Next step
Check your understanding
9 quick questions