On this page (12 sections)
- 🎯 When Things Go Wrong at Run Time
- 1️⃣ try and catch
- 2️⃣ Several catch Blocks and finally
- 3️⃣ Throwing Your Own Exceptions
- 4️⃣ Retrying Until the Input Is Valid
- 5️⃣ Checked and Unchecked Exceptions
- 6️⃣ Reading a Stack Trace
- 7️⃣ Errors Beginners Meet at Compile Time
- ⚠️ Common Mistakes
- ❓ Frequently Asked Questions
- ✅ Key Takeaways
- 🔁 Module 5 Recap
Java for Beginners · Module 5: Data and Methods
🎯 When Things Go Wrong at Run Time
In earlier lessons you saw programs crash with messages like ArithmeticException or NumberFormatException. These crashes are called exceptions. Instead of letting the program die, Java lets you catch an exception and decide what to do next. That is exception handling.
| Exception | Typical cause | Seen in |
ArithmeticException | integer divided by 0 | Lesson 12 |
ArrayIndexOutOfBoundsException | array index too big or negative | Lesson 21 |
StringIndexOutOfBoundsException | bad String index | Lesson 23 |
NullPointerException | method called on null | Lesson 23 |
NumberFormatException | parseInt on text like “abc” | Lesson 9 |
InputMismatchException | Scanner got the wrong kind of input | Lesson 10 |
StackOverflowError | recursion with no base case (an Error) | Lesson 26 |
Figure 3: Exceptions you have already met in this series.
1️⃣ try and catch
code that may fail
handle the error
cleanup, runs either way
Figure 1: The flow of try, catch and finally.
public class TryCatch {
public static void main(String[] args) {
try {
int a = 10, b = 0;
System.out.println("before division");
int c = a / b;
System.out.println("result = " + c);
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
System.out.println("program continues");
}
}
before division
Caught: / by zero
program continues
- When
a / bfails, Java jumps out of the try block at once. The lineresult = ...never runs. - The matching
catchblock receives the exception objecte.e.getMessage()gives a short description. - After the catch, the program carries on normally. Without the try-catch it would have stopped.
2️⃣ Several catch Blocks and finally
public class MultiCatch {
static void test(String text, int index) {
try {
int n = Integer.parseInt(text);
int[] arr = {10, 20, 30};
System.out.println("arr[" + index + "] / n = " + (arr[index] / n));
} catch (NumberFormatException e) {
System.out.println("Not a number: " + text);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + index);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} catch (Exception e) {
System.out.println("Something else: " + e);
} finally {
System.out.println("-- done with (" + text + ", " + index + ")");
}
}
public static void main(String[] args) {
test("5", 1);
test("abc", 1);
test("5", 7);
test("0", 1);
}
}
arr[1] / n = 4
— done with (5, 1)
Not a number: abc
— done with (abc, 1)
Bad index: 7
— done with (5, 7)
Cannot divide by zero
— done with (0, 1)
- One try block can have several catch blocks. Java uses the first one that matches, so list the more specific exceptions first.
catch (Exception e)at the end catches any other ordinary exception. Because it is the most general, it must come last.finallyruns every time: after a normal finish and after a caught exception. It is the right place to close files or connections.- Each of the four test calls shows a different path through the same code.
3️⃣ Throwing Your Own Exceptions
You can raise an exception yourself with throw when your method receives something unacceptable.
public class ThrowDemo {
static void setAge(int age) {
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Invalid age: " + age);
}
System.out.println("Age set to " + age);
}
static int safeDivide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
return 0;
} finally {
System.out.println("safeDivide finished");
}
}
public static void main(String[] args) {
setAge(20);
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
System.out.println("safeDivide(8, 2) = " + safeDivide(8, 2));
System.out.println("safeDivide(8, 0) = " + safeDivide(8, 0));
}
}
Age set to 20
Rejected: Invalid age: -5
safeDivide finished
safeDivide(8, 2) = 4
safeDivide finished
safeDivide(8, 0) = 0
throw new IllegalArgumentException(...)stopssetAgeimmediately, and the caller decides how to react.finallyruns even though the method returns insidetryorcatch. Both calls print “safeDivide finished”.
4️⃣ Retrying Until the Input Is Valid
Exception handling combined with a loop (Lesson 18) is the standard way to ask the user again after bad input.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = 0;
while (true) {
System.out.print("Enter your age: ");
String line = sc.nextLine();
try {
age = Integer.parseInt(line.trim());
break;
} catch (NumberFormatException e) {
System.out.println("Please type digits only.");
}
}
System.out.println("Age = " + age);
}
}
Enter your age: abc
Please type digits only.
Enter your age: 12x
Please type digits only.
Enter your age: 21
Age = 21
- The program reads the whole line as text, then tries to convert it. This avoids the Scanner newline trap and the
InputMismatchExceptionfrom Lesson 10. - When the conversion works,
break(Lesson 20) leaves the loop. Otherwise the catch prints a hint and the loop repeats. trim()removes the spaces around ” 21 ” (Lesson 24).
5️⃣ Checked and Unchecked Exceptions
ThrowableErrorserious JVM problems (OutOfMemoryError): do not catch
Exceptionproblems your program can handle
IOException, FileNotFoundException
RuntimeExceptionArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException
Figure 2: A simplified view of the exception family.
Unchecked exceptions (subclasses of RuntimeException) are usually programming mistakes, so Java does not force you to handle them. Checked exceptions describe problems outside your control, such as a missing file, so the compiler forces you to handle them.
import java.io.FileReader;
import java.io.IOException;
public class Checked {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("missing.txt");
fr.close();
} catch (IOException e) {
System.out.println("File problem: " + e.getMessage());
}
}
}
File problem: missing.txt (No such file or directory)
- Opening a file can fail for reasons the programmer cannot prevent, so Java makes you wrap it in try-catch (or declare
throwsin the method heading). - Files and streams are covered in more depth in the next Java series.
6️⃣ Reading a Stack Trace
maina()b(): exception thrown hereb, a, main (the stack trace lists them in that order) and the program stops.Figure 4: An uncaught exception travels up the call stack.
public class Unc {
static void a() { b(); }
static void b() { int[] x = new int[2]; x[5] = 1; }
public static void main(String[] args) {
System.out.println("start");
a();
System.out.println("never printed");
}
}
start
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2
at Unc.b(Unc.java:3)
at Unc.a(Unc.java:2)
at Unc.main(Unc.java:6)
- First line: what went wrong, with the exception name and message.
- Following lines: where. The top line (
Unc.b, line 3) is where it happened. The lines below show who called it. - The line “never printed” is skipped because nothing caught the exception.
- To fix a crash, read the first line, then jump to the first line that names your class.
7️⃣ Errors Beginners Meet at Compile Time
Not handling a checked exception
import java.io.FileReader;
public class Bad1 {
public static void main(String[] args) {
FileReader fr = new FileReader("data.txt");
}
}
Bad1.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(“data.txt”);
^
1 error
A general catch before a specific one
public class Bad2 {
public static void main(String[] args) {
try {
int x = 5 / 0;
} catch (Exception e) {
System.out.println("general");
} catch (ArithmeticException e) {
System.out.println("specific");
}
}
}
Bad2.java:7: error: exception ArithmeticException has already been caught
} catch (ArithmeticException e) {
^
1 error
Exceptionalready catchesArithmeticException, so the second block could never run. Put specific catches first.
try with nothing after it
public class Bad3 {
public static void main(String[] args) {
try {
System.out.println("hello");
}
System.out.println("no catch");
}
}
Bad3.java:3: error: ‘try’ without ‘catch’, ‘finally’ or resource declarations
try {
^
1 error
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Empty catch block: catch (Exception e) { } | Hides errors silently | At least print the message |
Exception caught before specific types | Compile error | Most specific first |
| Using try-catch instead of checking a simple condition | Slow and unclear | Check b != 0 when you can |
| Putting too much code in one try block | Unclear which line failed | Keep the try block small |
Catching Error types | JVM-level problems cannot be fixed | Catch Exception types only |
| Forgetting that code after the failing line is skipped | Variables left unset | Initialise before the try |
❓ Frequently Asked Questions
Q1. What is the difference between throw and throws?throw raises an exception at one place. throws in a method heading warns callers that the method may raise a checked exception.
Q2. Does finally run after System.exit()?
No. System.exit stops the JVM immediately.
Q3. Can I catch two exceptions in one block?
Yes: catch (NumberFormatException | ArithmeticException e).
Q4. Can I create my own exception class?
Yes, by extending Exception or RuntimeException. That needs inheritance, which comes in the OOP series.
✅ Key Takeaways
- Exceptions are run-time problems.
try/catchlets the program recover instead of crashing. - Order catch blocks from most specific to most general. The first match wins.
finallyalways runs, so use it for cleanup.throwraises your own exception, for example when an argument is invalid.- Checked exceptions must be handled or declared. Unchecked ones (RuntimeException) need not be.
- Read a stack trace from the top: what failed, then where.
🔁 Module 5 Recap
Lessons 21 to 28 covered arrays, strings, methods, recursion, ArrayList and exceptions. You can now store data, process text, split a program into methods and handle errors. In the last module you will meet objects, the idea Java is built around, and then combine everything in mini-programs.
🎓 Practice questions: (1) Write a program that reads two numbers as text and prints their quotient, handling both a non-number and a zero divisor. (2) Why mustcatch (Exception e)come aftercatch (ArithmeticException e)? (3) What doesfinallyprint in a method that returns insidetry? (4) Write a methodgetElement(int[] a, int i)that returns -1 instead of crashing for a bad index. (5) Read the stack trace of any crash from your own programs and explain each line.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java