【Java入門】Handling Exceptions（例外処理）

![2021-08-12_14h33_21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/a72b8d6c-edb3-23e0-b02e-0f1dc79baafd.png)

#もくじ
>**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.**

```java: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.**

```java: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.**

```java: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.**

```java: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.**

```java: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!
```

#参考資料

https://amzn.to/3g1mOx4

**Chapter 8 Handling Exception**
<a href="https://www.amazon.co.jp/Java-All-One-Dummies-Computer/dp/111968045X?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&dchild=1&keywords=java+all-in-one&qid=1628804220&sr=8-2&linkCode=li2&tag=e0557109-22&linkId=43076bbf1c8fe0309559e241fd15ef0a&ref_=as_li_ss_il" target="_blank"><img border="0" src="//ws-fe.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=111968045X&Format=_SL160_&ID=AsinImage&MarketPlace=JP&ServiceVersion=20070822&WS=1&tag=e0557109-22" ></a><img src="https://ir-jp.amazon-adsystem.com/e/ir?t=e0557109-22&l=li2&o=9&a=111968045X" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />