프로그램 실행중 오작동하는것
정의 : 프로그램 실행시 예외에 대비한 코드
목적 : 프로그램의 비정상 종료막기, 정상적인 실행유지
int number = 100;
int result = 0;
for(int i = 0; i < 10; i++) {
try {
result = number / (int) (Math.random() * 10);
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("0");
}
}
catch절 무시
Exception e = new Exception("고의로 예외발생"); // 1번방식
예외클래스는 2개로 나눌수 있다.
Exception
클래스와 그 자손클래스들RuntimeException
클래스와 자손클래스// try catch문으로 감싸야한다.
throw new Exception(); // 컴파일에러
// 컴파일시 문제되지 않는다.
throw new RuntimeException(); // // 비정상에러
PrintStream ps = null;
try {
ps = new PrintStream("error2.log");
System.out.println(0/0); // 예외발생
System.out.println(1);
} catch(ArithmeticException ae) { // true
System.out.println(12);
ae.printStackTrace();
ps.println("예외 : " + ae.getMessage());
System.err.println("err : " + ae.getMessage()); // 파일로저장
System.out.println(ae.getMessage());
} catch (Exception e) {
// 조상클래스 Exception사용
// instanceof로 true인데 위에서 수행되서
// 2는 출력안됨
System.out.println(2);
}
/*
if
elseif
else
구조라고 생각하면될듯
*/
메서드정보
와 예외메시지
출력try문이 끝나고 finally블럭으로 이동한다.
try문에서 return을 만나도 finally가 수행된다.
throws Exception1, Exception2 { }
throws
는 선언할때
throw
는 메서드 몸통에서
throws를 쓰면
java.lang.Exception
at ExceptionEx18.method2 (ExceptionEx18.java:12)
at ExceptionEx18.method1 (ExceptionEx18.java:8)
at ExceptionEx18.main (ExceptionEx18.java:4)
void method1() {
try {
throw new Exception();
} catch(Exception e) {}
}
method1();
위처럼 사용하면 정상작동하지만 어디서 예외가 발생됐는지 알 수 없다.
void method1() throws Exception {
throw new Exception();
}
try {
method1();
} catch(Exception e) {}
위처럼 사용해야 method1()
을 호출한 부분에서 에러가 났다는것을 알 수있다.
메서드 내에서 예외처리
호출쪽하는 쪽
에서 처리 public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
System.out.println("에러2");
}
}
static void method1() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("에러1");
throw e;
}
}
throw e
로 호출쪽에도 예외가 발생되게 한다.
throw e
가 없으면 에러1만 출력된다.
개발자가 직접 예외를 만들 수 있다.
public class Main {
public static void main(String[] args) {
try {
// throw MyException으로 돼있어서
// catch로 갈수있다.
test();
} catch (MyException e) {
System.out.println("에러 : " + e.getMessage());
}
}
// 에러 메서드
public static void test() throws MyException {
throw new MyException("ERR");
}
}
// Exception 상속받기
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
에러 : ERR
출력
정리
Exception안에 RuntimeException이 있다.
예외가 발생하면 catch문에서 instanceof로 예외클래스랑 비교해서 처리됨