【Java入門】Handling Exceptions(例外処理)


もくじ

1,Handling Exceptions
2,Another example
3,Using a finally Block
4,Catching FileNotFoundException
5,Throwing Your Own Exceptions

1, Handling Exceptions

Here's a program that divides two number and uses a try/catch statement to catch an exception if the second number turns out to be zero.

Main.java
public class Main {

    public static void main(String[] args) {

        int a = 5;
        int b = 0;

        try {
            int c = a / b;
        } catch (ArithmeticException e) {
            System.out.println("Oops, you can't divide by zero.");
        }
    }
}

When you run this program, the following is displayed on the console.

コンソール
Oops, you can't divide by zero.

2, Another example

This shows a simple example of a program that uses a method to get a valid integer from the user.

Main.java
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        System.out.print("Enter an integer: ");
        int i = GetAnInteger();
        System.out.println("You entered " + i);

    }

    public static int GetAnInteger() {
        while (true) {
            try {
                return sc.nextInt();

            } catch (InputMismatchException e) {
                sc.next();
                System.out.print("That's not an integer. Try again: ");
            }
        }
    }
}

Here's what the console might look like for a typical execution of this program.

コンソール
Enter an integer: three
That's not an integer. Try again: 3.01
That's not an integer. Try again: 3
You entered 3

3, Using a finally Block

A finally block is a block that appears after any of the catch blocks for a statement.

Main.java
public class Main {

    public static void main(String[] args) {

        int answer = 0;

        try {
            answer = divideTheseNumbers(5, 0);

        } catch (Exception e) {
            System.out.println("Tried twice, still didn't work!");
        }

        System.out.println("Answer is: " + answer);

    }

    public static int divideTheseNumbers(int a, int b) {

        int c;
        try {

            c = a / b;
            System.out.println("It worked!");

        } catch (Exception e) {
            System.out.println("Didn't work the first time.");
            c = a / b;
            System.out.println("It worked the second time!");
        } finally {
            System.out.println("Better clean up my mess.");
        }

        System.out.println("It worked after all.");
        return c;

    }
}

Here's the console output the program.

コンソール
Didn't work the first time.
Better clean up my mess.
Tried twice, still didn't work!
Answer is: 0

4, Catching FileNotFoundException

One way to deal with the FileNotFoundException is to catch it by using an ordinary try statement.

Main.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Main {

    public static void main(String[] args) {

        openFile("C:\\test.txt");

    }

    public static void openFile(String name) {
        try {
            FileInputStream f = new FileInputStream(name);
            System.out.println(f);

        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}

In this example, the message "File not found." is displayed if the file doesn't exist.

コンソール
File not found.

5, Throwing Your Own Exceptions

Here's a program that demonstrates the basic structure of a method that throws an exception.

Main.java
public class Main {

    public static void main(String[] args) {

        try {
            doSomething(true);
        } catch (Exception e) {
            System.out.println("Exception!");
        }
    }

    public static void doSomething(boolean t) throws Exception {
        if (t) {
            throw new Exception();
        }
    }
}

Here the doSomething method accepts a boolean value as a parameter. If this value is true, it throws an exception.

コンソール
Exception!

参考資料

Chapter 8 Handling Exception