try-catch
자바에서는 try-catch 구조를 사용하여 예외를 처리한다.
구조는 아래와 같다.
try{
// 예외가 발생할 수 있는 코드
}catch(Exception e){
// 예외를 처리하는 코드
}
예외는 크게 두 가지로 구분할 수 있다.
- Checked Exception : 컴파일러가 자동으로 오류가 발생하면 알려줌. 예외 처리 강제
- Runtime Exception : 컴파일러가 검사하지 않음. 예외 처리 강제하지 않음.
0으로 나누는 예외 처리
public class DivideByZero{
public static void main(String[] args){
try{
int result = 10 / 0 // 예외 발생
} catch(ArithmeticException e){
System.out.println("0으로 나눌 수 없습니다.");
}
}
try 안에 예외가 발생하면 catch안의 코드가 실행된다.
예외 떠넘기기
class Cal3 {
void divide(int num) throws Exception { // throws로 main에서 try catch 강제
System.out.println(10 / num);
}
}
public class TryEx05 {
public static void main(String[] args) {
Cal3 c3 = new Cal3();
try {
c3.divide(0);
} catch (Exception e) {
System.out.println("0으로 나누지 마요");
}
}
}
오류 강제 발생
throw new RuntimeException("오류 강제 발생"); // 오류를 강제로 발생 시킴

Share article