Nearby lessons

64 of 125

Java - throw and throws

📌 What You Will Learn
  • What an exception is and why programs crash
  • The try, catch, finally structure
  • Checked vs unchecked exceptions (with the updated rule)
  • throw vs throws
  • Creating your own (custom) exceptions
  • try-with-resources — the modern way

throw and throws is a core concept of the Java language. This lesson explains throw and throws with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

throw and throws

  • throw — used to throw an exception yourself, inside a method. throw new ArithmeticException("message");
  • throws — written in the method declaration, telling the caller: 'this method may throw these exceptions, you handle them'.

Simple memory trick: throw throws (an action, inside body), throws threatens (a warning, in the signature).

Example01
JCode Cell
1class ThrowThrowsDemo {
2 public static void main(String[] args) {
3 try {
4 checkAge(15);
5 } catch (Exception e) {
6 System.out.println(e.getMessage());
7 }
8 }
9 
10 static void checkAge(int age) throws Exception { // declaration
11 if (age < 18) {
12 throw new Exception("Age must be 18 or above"); // actual throw
13 }
14 System.out.println("Welcome");
15 }
16}
Output
Age must be 18 or above
📝 Key Takeaways
  • Exception = a run-time problem that stops the program; handling prevents the crash.
  • try keeps risky code, catch handles the problem, finally always runs.
  • Checked exceptions must be handled; unchecked (RuntimeException) are optional to handle.
  • throw throws an exception; throws warns that a method may throw one.
  • Custom exceptions extend Exception or RuntimeException for business rules.
  • try-with-resources (Java 7+) closes files/connections automatically.
  • Errors (like OutOfMemoryError) are system problems — not meant to be caught.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1