Java 예외처리

김정훈·2024년 4월 23일

Java

목록 보기
23/48

예외처리

1. 오류와 예외

오류(Error) : 시스템의 오류, JVM 오류(통제 불가)
예외(Exception) : 코드 상의 오류(통제 가능한 오류)

2. 예외처리 목적

  • 예외가 발생하면 프로그램 중단! -> 프로그램 중단을 막기 위한 조치
  • 예외처리의 목적 : 예외가 발생시 적절한 조치 -> 서비스 중단을 막는 것

3. 예외 클래스의 종류

      Throwable 
	  
Error           Exception
					

1) Exception을 바로 상속 받은 예외 클래스

예) java.io.IOException / 파일을 읽을때, 쓸때 (FileInputStream, FileOutputStream)
java.io.FileNotFoundException

  • 예외있든 없든 처리가 안되어 있으면 컴파일 X
  • 예외의 체크는 컴파일시 체크, 예외가 있으면 컴파일 X
  • 예외가 발생하든 안하든 반드시 적절한 예외 처리가 필요한 예외
  • 엄격한 예외, 형식을 매우 중시
public class Ex02 {
    public static void main(String[] args) {
        //Thorw new FileNotFoundException(...)
        //무조건 Thorw가 되어있다.
        FileInputStream fis = new FileInputStream("a.txt");
    }

2) RuntimeException을 중간에 상속 받은 예외 클래스

예) java.lang.ArithmethicException : 0으로 나눌때 발생

  • 예외가 발생하더라도 컴파일 O, class 파일 생성
  • 예외의 체크는 실행 중 체크, 실행이 되려면? class 파일 필요(컴파일은 된다...)
  • 유연한 예외, 형식은 X

참고)

java.exe : 클래스파일 실행
javac.exe : java -> class 컴파일

4. 예외 처리하기

1) try ~ catch문

 try {
	// 예외가 발생할 가능성이 있는 코드 
 } catch (예외 객체 ....) {
	// 예외 발생시 처리할 코드 
 }
public class Ex02 {
    public static void main(String[] args) {
        //Thorw new FileNotFoundException(...)
        try{
            FileInputStream fis = new FileInputStream("b.txt");
            System.out.println("파일처리");
        }catch(FileNotFoundException e){
            System.out.println("예외발생");
        };
        System.out.println("중요한 실행코드");
    }
}
public class Ex01 {
    public static void main(String[] args) {
        try{
            int num1 = 10;
            int num2 = 0;
            int result= num1 / num2;
            System.out.println(result);
        } catch (ArithmeticException e){
            e.printStackTrace();
        }
        System.out.println("매우중요한코드");
    }
}

참고

예외 발생
throw 예외객체;
예외, 오류 -> 원인을 확인을 하는것이 중요
예외 클래스 주요 메서드 : 정보확인
java.lang.Throwable

  • String getMessage() : 오류 메세지 확인
  • void printStackTrace() : 원인발생한 위치부터 ~ 파생된 위치...
public class Ex02 {
    public static void main(String[] args) {
        //Thorw new FileNotFoundException(...)
        try{
            FileInputStream fis = new FileInputStream("b.txt");
        }catch(FileNotFoundException e){
            String message = e.getMessage();
            System.out.println(message);
        };
    } 
    //getMessage()을통해 오류의 원인을 확인.
    //> b.txt (지정된 파일을 찾을 수 없습니다)

2) try-catch-finally문

try {

} catch (...) {
		...
} finally {
// 예외가 발생하든 안하든 항상 실행되는 코드 
// return 하더라도 코드가 실행 
}
public class Ex04 {
    public static void main(String[] args) {
        try{
            FileInputStream fis = new FileInputStream("d.txt");
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }finally {
            System.out.println("finally");
        }
    }
}

3) 자원해제 cloase()

  • 자원을 소비하는 객체 - FileInputStream, FileOutputStream, Connection, PrepareStatement
  • 자원 해제 → 애플리케이션 종료시에 해제
  • 서버는 종료 X -> 자원해제를 하지 않으면 메모리 부족 현상 발생
  • 자원해제를 적절하게 해야 된다.

finally에 자원해제를 해서 오류가 발생하든 안하든 해제를 하도록 해야한다.

public class Ex04 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try{
            fis = new FileInputStream("a.txt");
            System.out.println("파일작업");
        }catch (IOException e){
            System.out.println(e);
            e.printStackTrace();
        }finally {
            System.out.println("finally");
            if (fis != null){
                try{
                    fis.close();
                } catch (IOException e)
                {
                    
                }
            }
            System.out.println("자원해제완료");

        }
    }
}

4) try-with-resources문

  • JDK7에서 추가
  • 자원 해제를 자동
try ( 해제할 자원 객체;
해제할 자원 객체 ...) {
// 예외가 발생할 가능성이 있는 코드 
	
} catch(예외 객체 ...) {
	}
public class Resource implements AutoCloseable{
    @Override
    public void close() throws Exception {
        System.out.println("자원해제!");
    }
}
public class Ex01 {
    public static void main(String[] args) {
        try(Resource res = new Resource()){
            //res가 AutoCloasable 인터페이스 구현 객체인지 체크 → close()메서드 자동호출
            /* 로직
            AutoCloseable auto = res;
            auto.close();
            */
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

자원 자동해제의 기준
AutoCloseable 인터페이스의 구현 클래스 :close() 메서드를 자동 호출

참고)
instanceof

5. 예외 처리 미루기

1) 예외 처리를 미루는 throws 사용하기

  • 메서드를 호출 하는쪽에서 예외 처리 전가
  • 전가시키는 예외에 대해서 명시(throws)
    메서드 매개변수 뒤쪽에 throws 전가할 예외 작성
  • Exception을 상속 받은 경우(RuntimeException이 없는 경우)

2) 다중 예외 처리

예외가 다중 발생할 때에는 catch문을 다중으로 사용하여 처리한다.

public class Ex01 {
    public static void main(String[] args) {
        try{
            int num1 = 10;
            int num2 = 0;
            int result= num1 / num2;
            String str = null;
            System.out.println(str.toUpperCase());
            System.out.println(result);
        } catch (ArithmeticException e){
            e.printStackTrace();
        } catch(NullPointerException e){
            e.printStackTrace();
        } catch(Exception e){
        	e.printStackTrac();

        System.out.println("매우중요한코드");
    }
}

3) 사용자 정의 예외

Exception

  • JDK 기본 정의 예외 외에 따로 작성하는 예외
public class UserPwException extends Exception{
    public UserPwException(String message){
        super(message);
    }
}
 - - - - - - - - - - - - - - - - - - - - - 
public class UserIdException extends Exception {
    public UserIdException(String message){
        super(message);
    }
}
 - - - - - - - - - - - - - - - - - - - - - 
public class LoginService {
    public void login(String userId, String userPW) {
        //userID = user01, userPw = 123456
        try {
            if (!userId.equals("user01")) {
                throw new UserIdException("아이디가 일치하지않음");
            }

            if (!userPW.equals("123456")) {
                throw new UserPwException("비밀번호가 일치하지않음");

            }
            System.out.println("로그인성공");
        }catch (UserIdException | UserPwException e){
            System.out.println(e.getMessage());
        }
    }
}
 - - - - - - - - - - - - - - - - - - - - - 
public class Ex01 {
    public static void main(String[] args) {
        LoginService log = new LoginService();
        log.login("user01","123456");
    }
}
profile
안녕하세요!

0개의 댓글