JAVA - 7. 예외처리

CodeModel·2024년 3월 5일
0

자바

목록 보기
8/8

try catch finaly

try - 수행할 코드, 예외 가능성이 있는 코드들
catch(Exception e) - 예외 처리
finaly - 예외 발생 여부 상관 없이 실행하는 코드, 생략 가능하다

    public class ExceptionExam {
        public static void main(String[] args) {
            int i = 10;
            int j = 0;
            try{
                int k = i / j;
                System.out.println(k);
            }catch(Exception e) {
                System.out.println("0으로 나눌 수 없습니다. : " + e);
            }finally {
                System.out.println("오류가 발생하든 안하든 무조건 실행되는 블록입니다.");
            }
        }
    }
    

Throws

Throws는 예외가 발생했을때 예외를 호출한 쪽에서 처리하도록 하게 한다

    public class ExceptionExam2 {

        public static void main(String[] args) {
            int i = 10;
            int j = 0;
            try{
                int k = divide(i, j);
                System.out.println(k);
            } catch(ArithmeticException e){
                System.out.println("0으로 나눌수 없습니다.");
            }

        }

        public static int divide(int i, int j) throws ArithmeticException{
            int k = i / j;
            return k;
        }

    }

Exception 발생시키기

강제로 오류를 발생시키는 throw

    public class ExceptionExam3 {   
        public static void main(String[] args) {
            int i = 10;
            int j = 0;
            try{
                int k = divide(i, j);
                System.out.println(k);
            }catch(IllegalArgumentException e){
                System.out.println("0으로 나누면 안됩니다.");
            }           
        }

        public static int divide(int i, int j) throws IllegalArgumentException{
            if(j == 0){
                throw new IllegalArgumentException("0으로 나눌 수 없어요.");
            }
            int k = i / j;
            return k;
        }   
    }
profile
개발자가 되기 위한 일기

0개의 댓글