본문 바로가기
Java

[JAVA] Exception Handling

by 꿈나무 김땡땡 2019. 11. 20.

1. Common Exceptions

  • ArithmeticException: Something went wrong during an arithmetic operation; for example, division by zero.
  • NullPointerException: You tried to access an instance variable or invoke a method on an object that is currently null.
  • ArrayIndexOutOfBoundsException: The index you are using is either negative or greater than the last index of the array (i.e., array.length-1).
  • FileNotFoundException: Java didn’t find the file it was looking for.
  • IllegalArgumentException : 매개변수가 의도하지 않은 상황을 윱라할 때
  • IllegalStateException : 메소드를 호출하기 위한 상태가 아닐 때
  • Exception : exception 전체를 의미

2. Error Handling

(1) Try / Catch

 

try { 

// Block of code to try 

} catch (NullPointerException e) {   

// Print the error message like this:  

System.err.println("NullPointerException: " + e.getMessage());  

// Or handle the error another way here  

}

 

Catch 안에는 System.err.println()으로 기입 (System.out.println()이 아님)

 

try {

  //  Block of code to try

} catch (NullPointerException e) {

  //  Code to handle a NullPointerException

} catch (ArithmeticException e) {

  //  Code to handle an ArithmeticException

}

 

 

 

  • 생활코딩의 example
package org.opentutorials.javatutorials.exception;
class Calculator{
    int left, right;
    public void setOprands(int left, int right){
        this.left = left;
        this.right = right;
    }
    public void divide(){
        try {
            System.out.print("계산결과는 ");
            System.out.print(this.left/this.right);
            System.out.print(" 입니다.");
        } catch(Exception e){
            System.out.println("\n\ne.getMessage()\n"+e.getMessage()); // 오류 메시지
            System.out.println("\n\ne.toString()\n"+e.toString()); // 오류 메시지 상세
            System.out.println("\n\ne.printStackTrace()"); // 오류 메시지 위치 등 상세
            e.printStackTrace();
        }
    }
} 
public class CalculatorDemo {
    public static void main(String[] args) {
        Calculator c1 = new Calculator();
        c1.setOprands(10, 0);
        c1.divide();
         
        Calculator c2 = new Calculator();
        c2.setOprands(10, 5);
        c2.divide();
    }
}

 

 

 

  • 문법 설명
try {
  예외의 발생이 예상 되는 로직
} catch(예외클래스 인스턴스) {
  예외가 발생 했을 때 실행 되는 로직
} finally {
  예외 여부와 관계없이 실행되는 로직
}

 

3. Error 관련 메소드

  1. e.getMessage() : 오류에 대한 기본적인 내용
    >  예시 : /by zero
  2. e.toString() : e.getMessage()보다 더 자세한 예외 정보를 제공
    > 예시 :  java.lang.ArithmeticException: / by zero
  3. e.printStackTrace() : 가장 자세한 예외 정보 제공
    > 예시 :
    java.lang.ArithmeticException: / by zero

    at org.opentutorials.javatutorials.exception.Calculator.divide(CalculatorDemo.java:11)
    at org.opentutorials.javatutorials.exception.CalculatorDemo.main(CalculatorDemo.java:25)

'Java' 카테고리의 다른 글

[Java] Java로 배우는 자료구조 : 변수, 배열, 반복문  (0) 2019.12.16
[JAVA] BOJ_2739  (0) 2019.11.22
[JAVA] BOJ_2741  (0) 2019.11.22

댓글