Nearby lessons

65 of 125

Java - Predefined Exceptions

📌 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

Predefined Exceptions is a core concept of the Java language. This lesson explains Predefined Exceptions — When Each One Comes and Reading an Exception Message — Three Parts with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Predefined Exceptions — When Each One Comes

ExceptionWhen it is raised
ArithmeticExceptionDividing a number by zero, or other math errors
NullPointerExceptionCalling a method/field on a reference that is null
ArrayIndexOutOfBoundsExceptionAccessing an index outside the array's range
NumberFormatExceptionConverting an invalid String to a number (e.g., Integer.parseInt("abc"))
ClassNotFoundExceptionClass.forName("com.example.X") cannot find the class
Example01
JCode Cell
1class ExceptionsDemo {
2 public static void main(String[] args) {
3 // ArithmeticException
4 // int x = 10 / 0;
5 
6 // NullPointerException
7 String s = null;
8 // s.length();
9 
10 // ArrayIndexOutOfBoundsException
11 int[] arr = {1, 2, 3};
12 // System.out.println(arr[5]);
13 
14 // NumberFormatException
15 // int n = Integer.parseInt("abc");
16 
17 System.out.println("Uncomment any line above to see that exception");
18 }
19}

Reading an Exception Message — Three Parts

Every exception message on the command prompt has three parts. Learn to read them:

The stack trace (the lines starting with at) tells you exactly which line caused the problem — your first debugging tool.

Example02
JCode Cell
1Exception in thread "main" java.lang.ArithmeticException: / by zero
2 at Test.main(Test.java:7)
3 
4Part 1 Exception name : java.lang.ArithmeticException
5Part 2 Description : / by zero
6Part 3 Location : Test.java:7 (file name and line number)
📝 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