1. 예외의 계층 구조 

Exception 계층구조

  • 객체를 예외로 전달하기 위해 Throwable형으로 되어 있다. 
  • Error의 경우 시스템이 종료되어야 할 수준의 심각한 문제. (ex. OutOfMemoryError)
  • Excepthon의 경우 로직에서 발생한 실수.(ex.IllegalArgumentException)
    • RuntimeException : 실행시 발생
    • Exception : 컴파일시 발생

2. 예외 예시 

  • try-catch
package org.example;

public class Sample {
    public void finallyPrint() {
        System.out.println("ok thanks.");
    }

    public void exceptionPrint() {
        System.out.println("excpetion.");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        int c;
        try {
            c = 4 / 0;
        }
        catch (ArithmeticException e) {
            c = -1;
            sample.exceptionPrint();
        }
    }
}
  • try-catch-finally
package org.example;

public class Sample {
    public void finallyPrint() {
        System.out.println("ok thanks.");
    }

    public void exceptionPrint() {
        System.out.println("excpetion.");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        int c;
        try {
            c = 4 / 0;
        }
        catch (ArithmeticException e) {
            c = -1;
            sample.exceptionPrint();
        }
        finally {
            sample.finallyPrint();  // 예외에 상관없이 무조건 수행.
        }
    }
}

 

3.  사용자 정의 예외 

  • Exception을 상속 받음.
  • throw를 통해 예외를 강제로 발생 
package org.example;

class FoolException extends Exception {
}

public class Sample {
    public void sayNick(String nick) throws FoolException {
        if("fool".equals(nick)) {
            throw new FoolException();
        }
        System.out.println("당신의 별명은 "+nick+" 입니다.");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        try {
            sample.sayNick("fool");
            sample.sayNick("genious");
        } catch (FoolException e) {
            System.err.println("FoolException이 발생했습니다.");
        }
    }
}

 

 

'개발 > JAVA' 카테고리의 다른 글

인터페이스(interface)-JAVA  (0) 2023.02.06

1. 인터페이스의 특징

  • 다중 상속이 가능하게 해준다.
  • 추상 메소드와 상수만 선언 가능하다
  • 생성자 사용이 불가능하다(객체가 아니기 때문)
  • 메서드 오버라이딩이 필수이다.(오버라이딩을 안할 경우 컴파일 단계에서 에러가 발생한다.)

 

2. 인터페이스 사용하는 이유?

  • 자바에서 다중 상속을 가능하게 해준다. 자바는 class를 다중으로 상속하는 것은 불가능하다. diamond problem를 해결하기 위해 자바는 단일 상속만을 원칙으로 한다.  

mother과 father을 상속받은 child 입장에서 love()를 실행할 경우 어떤 함수를 실행 시켜야할지 모호함이 발생.

  • 코드의 종속성을 낮춰준다. 
    • 공통으로 필요한 특정 메소드를 인터페이스로 적용한다면, 각각의 메소드를 자유롭게 변경할 수 있다. 

 

3. 인터페이스 예시 

  • 인터페이스 상속시 "implements" 명령어를 사용 
  • Mother.java
package org.example;

public interface Mother {
    public abstract void love();
}
  • Father.java
package org.example;

public interface Father {
    public abstract void love();
}
  • Child.java
package org.example;

public class Child implements Mother, Father{
    @Override
    public void love() {
        System.out.println("i love you");
    }
}
  • Main.java
package org.example;

public class Main {
    public static void main(String[] args) {

        Child child = new Child();
        child.love();
    }
}

'개발 > JAVA' 카테고리의 다른 글

예외처리-JAVA  (0) 2023.02.06

+ Recent posts