Nearby lessons

66 of 125

Java - Custom (User-Defined) 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

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

Custom (User-Defined) Exceptions

Real projects create their own exception classes for their own business rules. You just extend Exception (checked) or RuntimeException (unchecked).

Example01
JCode Cell
1class InvalidMarksException extends Exception {
2 InvalidMarksException(String msg) {
3 super(msg);
4 }
5}
6 
7class Test {
8 public static void main(String[] args) {
9 try {
10 setMarks(-5);
11 } catch (InvalidMarksException e) {
12 System.out.println("Error: " + e.getMessage());
13 }
14 }
15 
16 static void setMarks(int m) throws InvalidMarksException {
17 if (m < 0 || m > 100)
18 throw new InvalidMarksException("Marks must be 0 to 100");
19 }
20}
Output
Error: Marks must be 0 to 100
📝 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