C
JV

C to Java

10 lessons

Progress0%
1Introduction to Java2Data Types3Strings4Arrays and Collections5Object-Oriented Programming6Exception Handling7Collections and Generics8Modern Java Features9Interfaces and Polymorphism10Threads and Concurrency
All Mirror Courses
C
JV
Exception Handling
MirrorLesson 6 of 10
Lesson 6

Exception Handling

Error handling in Java

Introduction

In this lesson, you'll learn about exception handling in Java. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
C
From C:

In C, you're familiar with error handling in java.

JV
In Java:

Java has its own approach to error handling in java, which we'll explore step by step.

The Java Way

Let's see how Java handles this concept. Here's a typical example:

JV
Java Example
// Java - exception handling
public int divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Division by zero");
    }
    return a / b;
}

// Usage
try {
    int result = divide(10, 0);
    System.out.println("Result: " + result);
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("Cleanup here");
}

Comparing to C

Here's how you might have written similar code in C:

C
C (What you know)
// C - error handling with return codes
int divide(int a, int b, int* result) {
    if (b == 0) {
        return -1; // error code
    }
    *result = a / b;
    return 0; // success
}

// Usage
int result;
if (divide(10, 0, &result) == -1) {
    printf("Error: division by zero\n");
} else {
    printf("Result: %d\n", result);
}
Mirror Card
C
From C:

You may be used to different syntax or behavior.

JV
In Java:

Exceptions separate error handling from normal flow

Mirror Card
C
From C:

You may be used to different syntax or behavior.

JV
In Java:

try/catch/finally blocks for handling

Mirror Card
C
From C:

You may be used to different syntax or behavior.

JV
In Java:

throws declares what exceptions a method can throw

Mirror Card
C
From C:

You may be used to different syntax or behavior.

JV
In Java:

finally runs regardless of exception

Step-by-Step Breakdown

1. Try-Catch-Finally

Exceptions provide structured error handling.

JV
Java
try {
    // Code that might throw
    FileReader fr = new FileReader("file.txt");
    int data = fr.read();
} catch (FileNotFoundException e) {
    // Handle file not found
    System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
    // Handle other IO errors
    System.out.println("IO error: " + e.getMessage());
} finally {
    // Always runs - cleanup here
    System.out.println("Cleanup");
}

2. Throwing Exceptions

Methods can throw exceptions and declare them in the signature.

JV
Java
// Declare that method throws exception
public void readFile(String path) throws IOException {
    FileReader fr = new FileReader(path);
    // if file doesn't exist, throws FileNotFoundException
    // which is a subclass of IOException
}

// Custom exceptions
public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public void setAge(int age) throws InvalidAgeException {
    if (age < 0) {
        throw new InvalidAgeException("Age cannot be negative");
    }
}

3. Checked vs Unchecked

Checked exceptions must be caught or declared. Unchecked can be ignored.

JV
Java
// Checked - must handle or declare
// IOException, SQLException, etc.
public void read() throws IOException {
    // ...
}

// Unchecked - don't need to declare
// RuntimeException, NullPointerException, etc.
public void process(String s) {
    if (s == null) {
        throw new NullPointerException("s cannot be null");
    }
}
Rule of Thumb
Use checked exceptions for recoverable conditions, unchecked for programming errors.

Common Mistakes

When coming from C, developers often make these mistakes:

  • Exceptions separate error handling from normal flow
  • try/catch/finally blocks for handling
  • throws declares what exceptions a method can throw
Common Pitfall
Don't assume Java works exactly like C. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • Exceptions separate error handling from logic
  • try/catch/finally for handling
  • throw to raise, throws to declare
  • Checked exceptions must be handled or declared
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your C code in Java to practice these concepts.
PreviousNext