VisualStudioTutor.com Java Tutorial All Lessons

Lesson 18 of 20

Exception Handling and Debugging

Handle runtime problems with try, catch, finally, validation, and debugging techniques.

Learning objectives

  • Distinguish compile-time errors from runtime exceptions.
  • Catch and handle an exception.
  • Use multiple catch blocks when appropriate.
  • Throw an exception for invalid method arguments.
  • Use a debugger to locate the actual source of a problem.

1. What is an exception?

An exception represents a problem that occurs while a program is running. Examples include invalid number conversion, missing files, and illegal array indexes.

Example: NumberFormatException

String text = "abc";
int number = Integer.parseInt(text); // throws NumberFormatException

2. try and catch

Put code that may fail inside try. Handle the expected failure in a matching catch block.

Example: safe numeric input

import java.util.Scanner;

public class SafeNumberInput {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        try {
            System.out.print("Enter a whole number: ");
            int number = Integer.parseInt(input.nextLine());
            System.out.println("You entered: " + number);
        } catch (NumberFormatException e) {
            System.out.println("That was not a valid whole number.");
        }

        input.close();
    }
}

3. finally

A finally block is intended for cleanup that should occur whether the try block succeeds or fails. For many modern resources, try-with-resources is even better because it closes resources automatically.

try {
    System.out.println("Trying operation...");
} catch (RuntimeException e) {
    System.out.println("Operation failed.");
} finally {
    System.out.println("Cleanup step.");
}

4. Throwing your own exception

public static void setMark(int mark) {
    if (mark < 0 || mark > 100) {
        throw new IllegalArgumentException("Mark must be from 0 to 100.");
    }

    System.out.println("Mark accepted: " + mark);
}

5. Debugging strategy

  1. Read the first useful exception message.
  2. Find the first stack-trace line that points to your own source file.
  3. Set a breakpoint just before that line.
  4. Inspect the variables involved.
  5. Step through the code and compare actual values with what you expected.

Mini project: validated mark entry

import java.util.Scanner;

public class ValidatedMark {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while (true) {
            try {
                System.out.print("Enter mark (0-100): ");
                int mark = Integer.parseInt(input.nextLine());

                if (mark < 0 || mark > 100) {
                    throw new IllegalArgumentException("Mark out of range.");
                }

                System.out.println("Accepted mark: " + mark);
                break;
            } catch (NumberFormatException e) {
                System.out.println("Please enter a whole number.");
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }

        input.close();
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
Catching Exception everywhereIt hides which failures you actually expect.Catch specific exception types when possible.
Empty catch blockThe program silently ignores a failure.Handle, report, or deliberately propagate the exception.
Using exceptions for normal control flowExceptions are for exceptional conditions, not ordinary branching.Use validation and normal conditions where appropriate.

Summary

Exception handling lets a program respond to failures instead of terminating without explanation. Lesson 19 applies these ideas to file input and output.