애플리케이션 개발/JAVA

[JAVA] 예외

sofiaaa 2022. 2. 2. 02:01
반응형

Chapter 14

try-catch

예외가 발생할 것 같은 문장을 try 안에 묶어준다.

public void arrayOutOfBoundsTryCatch(){
    int[] intArray = new int[5];
    try{
    	System.out.println("This code should run.");
    } catch (Exception e){
    	System.err.println("Exception occured");
    }
}

 

finally

어떠한 경우에도 반드시 실행되어야 한다.

public void arrayOutOfBoundsTryCatch(){
	int[] intArray = new int[5];
    try{
    	System.out.println("This code should run.");
    } catch (Exception e){
    	System.err.println("Exception occured");
    } finally {
    	System.out.println("Here is finally.");
    }
}

 

 

예외 3가지

  • checked exception
  • error
  • runtime exception 혹은 unchecked exception

 

java.lang.Throwable 클래스

모든 자바 클래스의 부모 클래스는 java.lang.Object 클래스이다.

이렇듯, Exeption과 Error의 공통 부모 클래스는 Throwable 클래스이다.

 

throws, throw

1.메소드를 선언할 때 매개 변수 소괄호 뒤에 throws라는 예약어를 적어주면, 호출한 메소드로 예외가 전달된다.
만약 메소드에서 두 가지 이상의 예외를 던질 수 있따면, 콤마로 구분하면 된다.

public void multiThrows() throws NullPointerException, Exception {

}

2. try 블록 내에서 예외를 발생시킬 경우, throw라는 예약어를 적어 준뒤 예외 객체를 생성하거나 생성되어 있는 객체를 명시해준다.

아 잘 모르겠다 ..

반응형

'애플리케이션 개발 > JAVA' 카테고리의 다른 글

[JAVA] JAVA  (0) 2022.02.02
[JAVA] String , 어노테이션  (0) 2022.02.02
[JAVA] 인터페이스  (0) 2022.02.02
[JAVA] 상속  (0) 2022.02.01
[JAVA] 접근 제어자 - public / protected / default / private  (0) 2022.02.01