Nearby lessons

59 of 125

Java - Exceptions Overview

📌 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

Exceptions Overview is a core concept of the Java language. This lesson explains What is an Exception?, Error vs Exception — Question and Answer and Pure Checked vs Partially Checked Exceptions with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is an Exception?

An exception is an event that happens during the running of a program and stops the normal flow. For example, dividing a number by zero, opening a file that does not exist, or accessing index 10 of a 5-element array.

Without handling, an exception makes the program crash suddenly and all work is lost. Exception handling is the art of catching these problems and giving the user a friendly message instead of a crash.

Example01
JCode Cell
1class CrashDemo {
2 public static void main(String[] args) {
3 int a = 10, b = 0;
4 System.out.println(a / b); // crash! ArithmeticException
5 }
6}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero

Error vs Exception — Question and Answer

First, understand that a problem in a program is either an Error or an Exception:

PointErrorException
What it isA serious system-level problemA problem in the program's logic/flow
ExamplesOutOfMemoryError, StackOverflowErrorArithmeticException, IOException
Can we catch it?Usually not (not meant to be caught)Yes — that is what exception handling is for
Who fixes itFix the design/code, or give more memoryHandle with try-catch

Errors are further divided by when they happen:

Type of errorWhen it happensExample
Compile-time errorWhile compilingnit i = 10; (lexical), missing ; (syntax), using undeclared variable (semantic)
Runtime errorWhile runningDividing by zero, array index out of bounds

Compile-time errors come in three kinds: lexical (wrong keywords/spelling), syntax (wrong structure), and semantic (meaning errors like wrong types). Runtime errors are mostly exceptions.

Pure Checked vs Partially Checked Exceptions

Checked exceptions are divided into two further types — a classic exam question:

TypeMeaningExamples
Pure checkedIts sub classes are ALL checked exceptionsIOException (all its children are checked)
Partially checkedHas at least one unchecked exception as a sub classException, Throwable (they include RuntimeException)

Simple memory: IOException is pure checked; Exception and Throwable are partially checked because they also cover RuntimeException.

The Exception Hierarchy (Quick Map)

Example04
JCode Cell
1Throwable
2 |-- Error (OutOfMemoryError, StackOverflowError - not caught)
3 `-- Exception
4 |-- IOException (checked) - file/network problems
5 |-- SQLException (checked) - database problems
6 `-- RuntimeException (unchecked)
7 |-- ArithmeticException - divide by zero
8 |-- NullPointerException - using null reference
9 |-- ArrayIndexOutOfBoundsException - bad array index
10 |-- NumberFormatException - wrong number format

Checked vs Unchecked Exceptions

Exceptions are divided into two big families:

PointChecked exceptionsUnchecked exceptions
Checked by compiler?Yes — compiler forces you to handle themNo — you may handle but are not forced
Parent classException (sub classes)RuntimeException (sub classes)
ExampleIOException, SQLExceptionArithmeticException, NullPointerException
CauseExternal things: file missing, network downProgramming mistakes
Must handle?Yes, with try-catch or throwsOptional (but good practice)
Trainer's Note: Updated knowledge: older trainers teach 'all checked exceptions must be caught'. That is still true. But from Java 7, the multi-catch and try-with-resources make handling much cleaner. Also remember Error is different from Exception — Errors (like OutOfMemoryError) are serious system problems we should not try to catch.
In simple words: Checked exceptions are forced by the compiler, unchecked ones are not. If a method may throw a checked exception you must catch it or declare it with throws, or the code will not compile at all.

Best Practices — Trainer's Checklist

  • Catch exceptions where you can do something meaningful — do not swallow them with an empty catch block.
  • Never catch a NullPointerException to hide a bug — find why the value is null instead.
  • Always close resources (use try-with-resources).
  • Log the exception details (stack trace) instead of just printing a message in production.
  • Throw specific exceptions (NumberFormatException) rather than a general Exception.
  • finally is the right place for cleanup that must run whether an error happened or not.
📝 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