프로그램에 문제가 발생했을 때, 그 문제로 인해 시스템 동작에 문제가 없도록 예외를 사전에 예방하는 코드를 작성한다
Exception 과 Error
예외는 소프트웨어 시스템적인 문제로 개발자가 대처할 수 있지만 에러는 물리적, 하드웨어적인 문제로 개발자가 대처할 수 없는 것이 차이
Exception
- Checked Exception : 예외처리를 반드시 해야하는 경우(네트워크, 파일 시스템 등)
- Unchecked Exception : 예외처리를 개발자의 판단에 맡기는 경우(데이터 오류 등)
Exception 클래스의 대표적인 하위클래스
- NullPointerException : 객체를 가리키지 않는 레퍼런스를 이용할 때
- ArrayIndexOutOfBoundException : 배열에서 존재하지 않는 인덱스를 가리킬 때
- NumberFormatException : 숫자데이터에 문자데이터 등을 넣었을 때
... 등등 많은 하위클래스가 있지만 외울 필요는 없다
예외처리 맛보기
public class No15_Exception {
public static void main(String[] args) {
int i = 10;
int j = 0;
int r = 0;
System.out.println("Exception Before");
try { // 예외 발생할만한 구문
r = i/j;
} catch (Exception e) { // catch로 잡는다
e.printStackTrace();
String msg = e.getMessage();
System.out.println("msg : "+msg);
}
System.out.println("Exception After");
}
}
실행결과
Exception Before
java.lang.ArithmeticException: / by zero
at Class.No15_Exception.main(No15_Exception.java:13)
msg : / by zero
Exception After
각각 예외처리, finally
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class No15_Exception2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, j;
ArrayList<String> list = null;
int[] iArr = {0, 1, 2, 3, 4};
System.out.println("Exception Before");
try {
System.out.println("input i : ");
i = sc.nextInt();
System.out.println("input j : ");
j = sc.nextInt();
System.out.println("i / j = "+ (i/j));
for(int k=0; k<6; k++) {
System.out.println("iArr["+k+"] : "+iArr[k]);
}
System.out.println("list.size(): "+list.size());
} catch (InputMismatchException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("예외 발생 여부와 상관없이 실행되는 finally");
}
System.out.println("Exception After");
}
}
// try에서 예외가 발생하면 그 이후의 try 구문은 실행되지 않는다
// catch는 Exception 하나로만 잡아도 되고 각각의 catch를 설정해도 된다
// finally는 예외발생과 상관없이 실행된다
throws : 예외 발생 시 직접 예외처리를 하지 않고 자신을 호출한 곳으로 던져버린다
public class No15_throws {
public static void main(String[] args) {
No15_throws th = new No15_throws();
try {
th.method1();
} catch (Exception e) {
e.printStackTrace();
}
}
public void method1() throws Exception{
method2();
}
public void method2() throws Exception{
method3();
}
public void method3() throws Exception{
System.out.println("10/0 = "+ (10/0));
}
}
// method3() 에서 발생한 예외 -> method2() 로 throws -> method1() 로 throws
예외를 내가 처리할 것인지 throws 할 것인지 잘 판단해야 한다
'Java' 카테고리의 다른 글
[Java] 데이터 입출력(2) BufferedReader, BufferedWriter (0) | 2021.08.09 |
---|---|
[Java] 데이터 입출력(1) FileInputStream, DataInputStream, FileOutputStream, DataOutputStream (0) | 2021.08.09 |
[Java] Collections(1)_List 인터페이스 (0) | 2021.08.02 |
[Java] StringBuffer, StringBuilder (0) | 2021.08.01 |
[Java] 람다식 (0) | 2021.08.01 |