Java 예외

예외의 처리

수업소개

자바에서 예외가 발생했을 때 이를 처리하는 방법을 소개합니다. 

 

 

 

강의

 

 

 

소스코드

https://github.com/egoing/java-exception/commit/2812c9af98d93bc9039cf224f32a825ff4b15caa

public class ExceptionApp {
    public static void main(String[] args) {
        System.out.println(1);
        int[] scores = {10,20,30};
        try {
            System.out.println(2);
            System.out.println(scores[3]);
            System.out.println(3);
            System.out.println(2 / 0);
            System.out.println(4);
        } catch(ArithmeticException e){
            System.out.println("잘못된 계산이네요.");
        } catch(ArrayIndexOutOfBoundsException e){
            System.out.println("없는 값을 찾고 계시네요 ^^");
        }
        System.out.println(5);
    }
}

 

댓글

댓글 본문
  1. jajada
    try 와 catch 를 사용한다.

    try 구문 안에서 작동하는 코드들 중에 예외가 터지는 것이 있다면 catch 구문 안에서 try 구문에서 발생한 예외 상황과 같은 예외를 찾은 이후 catch 안에 있는 코드를 실행한다.

    하지만 이 과정에서 다음과 같은 코드가 있을때.
    int[] scores = {10, 20, 30};
    System.out.println(1);

    try {
    System.out.println(2);
    System.out.println(scores[3]);
    System.out.println(3);
    System.out.println(2 / 0);
    System.out.println(4);
    } catch (ArithmeticException e) {
    System.out.println("잘못된 계산입니다.");
    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("존재하지 않는 배열입니다.");
    }
    System.out.println(3);

    출력
    1
    2
    존재하지 않는 배열입니다.
    3

    이렇게 나오게 된다.

    여기서 알 수 있는 점은 try 구문 중에서 예외가 발생하면 그 즉시 try 구문을 빠져 나가 catch 구문으로 이동해 그곳에 있는 코드를 실행하게 된다.

    그렇기에 try구문에 있던 3, 2/0, 4 와 같은 결과값이 출력되지 않고 그대로 빠져나가게 된 것이다.

    그렇다면 2개 이상의 예외가 발생한다고 예상하고 try 안에 그 2개의 예외가 발생할 가능성이 있는 코드를 전부 넣는다면 그 두개의 코드중 하나는 작동하지 않을 가능성이 생기기 때문에 try를 2개를 만들어야 한다는 말이 되고 이것은 극한의 비효율적인 행동이다.
  2. 당당
    2023.04.17
  3. Min Jupiter
    23.01.03
  4. 코딩이취미다
    예외 상황에 따라 별도로 처리를 해야 하나요?
    모든 예외를 처리 하는게 있을 것 같은데...
    있겠지....
  5. 나연
    2022년 2월 26일 (토) 완료

    ```java
    try {
    System.out.println(2 / 0);
    } catch (ArithmeticException e) {
    // e는 변수. 보통 "e"라고 이름 지음.
    System.out.println("Wrong calculation.");
    }
    ```
    - `System.out.println(2 / 0);` 실행을 시도한 후 `ArithmeticException`이 발생하면 `catch (ArithmeticException e)` 중괄호 안에 있는 코드 실행
    - `try` / `catch`를 사용하지 않으면 익셉션이 발생했을 때 거기서 프로그램이 멈춤
  6. 2021.08.31 완료
  7. oyuiw
    20201213
graphittie 자세히 보기