예외처리

프로그래밍/Java 2019. 12. 29. 22:38

예외처리

예외처리란 프로그램이 샐행과정에서 오류가 발생 했을 때 어플리케이션이 멈추는 것을 방지하기 위한 코딩기법이다.

프로그램을 개발할 때 컴파일 과정에서 일어나는 버그는 개발과정에서 수정할 수 있지만, 실제 운영할 때 이러한 버그가 생기면 심각하게는 운영중인 서비스가 죽어버리는 불상사가 생길 수도 있다. 이를 대비해 혹여, 운영중에 오류가 생겼더라도 다른 서비스에는 영향을 주지 않도록 하는 것이 예외처리이다.


try~catch문

try ~ catch 를 사용하여 예외처리.

package exception;

public class ArrayExceptionHandling {

    public static void main(String[] args) {
        int [] arr = new int[5]; // 정수열 배열의 크기가 5인 자료형 선언

        try {
            for(int i=0; i<=5; i++) {
                arr[i] = i; // 5번째에서 에러남.
                System.out.println(arr[i]);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
            System.out.println("예외 처리 부분");
        }
        System.out.println("프로그램 종료");
    }
}

  • 배열의 크기를 넘어서서 값을 할당하였기 때문에 에러가 발생한다.
  • 에러가 발생하면 catch 구문이 실행되고, 프로그램이 멈추지않고 실행되었다.

파일 예외처리1

package exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionHandling1 {

    public static void main(String[] args) {
//        FileInputStream fis = null;

        try {
            FileInputStream fis = new FileInputStream("a.txt");
        } catch (FileNotFoundException e) {
//            e.printStackTrace();
            System.out.println(e);
        }
        System.out.println("여기도 수행됩니다.");
    }
}

  • 존재하지 않는 파일 객체를 가져오려했다.
  • 에러가 발생하고 catch 부분에서 FileNotFoundException 구문을 출력하였다.

파일 예외처리2 - try ~ catch.. finally

package exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionHandling2 {

    public static void main(String[] args) {
        FileInputStream fis = null;

        try {
            fis = new FileInputStream("a.txt");
        } catch (FileNotFoundException e) {
            System.out.println(e);
            return;
        }finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("항상 수행 됩니다.");
        }
        System.out.println("여기도 수행 됩니다.");
    }

}

  • 에러가 발생한 후 catch 블록이 실행됐다.
  • 강제로 return을 수행함, 그래서 "여기도 수행 됩니다." 라는 구문을 실행되지 않는다.
  • catch블록에서 강제로 리턴을 했는데 finally 블록을 수행한다.
  • finally 블록은 반드시 실행되야하는 구문이다.
  • 코드가 성공하든 안하든 파일 객체는 반드시 닫아야하기 때문에 finally에 선언하였다.
  • 위에서는 finally에서 객체를 닫아주었지만 AutoCloseable 인터페이스를 구현하여 close 메서드를 실행할 수 있다.

예외처리 미루기

package exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ThrowsException {

    // 메서드의 리턴 타입이 클래스
    public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(fileName);
        Class c = Class.forName(className);
        return c;
    }

    public static void main(String[] args) {
        ThrowsException test = new ThrowsException();

        try {
            test.loadClass("a.txt", "java.lang.String");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

}
  • ThrowsExcetpion 객체를 생성하여 예외처리에 대한 메서드를 정의하였다.
  • Exception클래스는 catch 블록에서 가장 마지막에 있어야한다.
  • 만약 Exception클래스가 catch 블록 처음에 있게 되면 나머지 부분에서 이미 정의 되었다는오류가 발생한다. 그것은 Exception 클래스가 선언되면서 나머지 예외클래스들이 자동으로 상위 형변환 되기 때문이다.


사용자 정의 예외처리

Exception클래스를 상속받아, 사용자 정의 클래스 구현하기.


IDFormatException

package exception;

public class IDFormatException extends Exception{
    public IDFormatException(String message) {
        super(message);
    }
}

IDFormatTest

package exception;

public class IDFormatTest {

    private String userID;

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) throws IDFormatException {
        if(userID == null) {
            throw new IDFormatException("아이디는 null일 수 없습니다.");
        }else if(userID.length() < 8 || userID.length() > 20) {
            throw new IDFormatException("아이디는 8자 이상 20자 이하로 쓰세요.");
        }
        this.userID = userID;
    }

    public static void main(String[] args) {
        IDFormatTest test = new IDFormatTest();

        String userID = null;

        try {
            test.setUserID(userID);
        } catch (IDFormatException e) {
            System.out.println(e.getMessage());
        }

        userID = "1234567";

        try {
            test.setUserID(userID);
        } catch (IDFormatException e) {
            System.out.println(e.getMessage());
        }                
    }

}

  • IDFormatTest클래스의 사용자아이디를 세팅할 때 예외처리를 구현하였다.

출처: do it 자바프로그래밍

'프로그래밍 > Java' 카테고리의 다른 글

쓰레드  (0) 2020.05.10
스트림(파일)  (0) 2020.01.04
스트림  (0) 2019.12.27
람다식  (0) 2019.12.25
내부 클래스  (0) 2019.12.25
블로그 이미지

파니동

,