0으로 나눌 때 발생하는 ArithmeticException 예외 처리
try-catch 문을 이용하여 정수를 0으로 나누는 경우에 오류 안내문을 출력하고 다시 입력 받는 프로그램의 예제 코드는 다음과 같다.
package ch3n15;
import java.util.Scanner;
public class DivideByZeroHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("나뉨수를 입력하시오:");
int dividend = scanner.nextInt(); // 나뉨수 입력
System.out.print("나눗수를 입력하시오:");
int divisor = scanner.nextInt(); // 나눗수 입력
try {
System.out.println(dividend + "를" + divisor + " 로 나누면 몫은 " + dividend/divisor + "입니다.");
break;
}
catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다! 다시 입력하세요.");
}
}
scanner.close();
}
}
위 프로그램을 실행하여 예시로, 각각 100, 0을 입력하면 catch 문에서 예외 처리를 한다. catch 문을 실행 후 다시 while 문을 반복하고, try 문에서 정상적으로 나누기가 이루어지면 break 문을 이용하여 빠져나온다.
범위를 벗어난 배열에 접근할 때 발생하는 ArrayIndexOutOfBoundsException 예외 처리
배열의 인덱스가 범위를 벗어날 때 발생하는 ArrayIndexOutOfBoundsException을 처리하는 프로그램의 예제 코드는 다음과 같다.
package ch3n16;
public class ArrayException {
public static void main(String[] args) {
int[] intArray = new int[5];
intArray[0] = 0;
try {
for (int i = 0; i < 5; ++i) {
intArray[i + 1] = i + 1 + intArray[i];
System.out.println("intArray[" + i + "]" + " = " + intArray[i]);
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열의 인덱스가 범위를 벗어났습니다.");
}
}
}
입력 오류 시 발생하는 InputMismatchException 예외 처리
사용자가 정수가 아닌 문자를 입력할 때 발생하는 예외를 처리하며, 3개의 정수를 입력받아 합을 구하는 프로그램의 예제 코드는 다음과 같다.
package ch3n17;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("정수 3개를 입력하세요");
int sum = 0, n = 0;
for (int i = 0; i < 3; ++i) {
System.out.print(i + ">>");
try {
n = scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("정수가 아닙니다. 다시 입력하세요!");
scanner.nextLine();
--i;
continue;
}
sum += n;
}
System.out.println("합은 " + sum);
scanner.close();
}
}
정수가 아닌 문자열을 정수로 형변환 시 발생하는 NumberFormantException 예외 처리
문자열을 정수로 변환할 때 발생하는 NumberFormatException 예외를 처리하는 프로그램의 예제 코드는 다음과 같다.
package ch3n18;
public class NumException {
public static void main(String[] args) {
String[] stringNumber = {"23", "12", "3.141592", "998"};
int i = 0;
try {
for (i = 0; i < stringNumber.length; ++i) {
int j = Integer.parseInt(stringNumber[i]);
System.out.println("정수로 변환된 값은 " + j);
}
}
catch (NumberFormatException e) {
System.out.println(stringNumber[i] + "는 정수로 변환할 수 없습니다.");
}
}
}