Java

[Java] 멀티 catch 블럭, 예외 발생, checked와 unchecked (예외처리1-3)

codeStudy123 2022. 1. 5. 23:22

 

📖 멀티 catch블럭

 

 

JDK 1.7부터 여러 catch블럭을 '|' 기호를 사용하여, 하나의 catch블럭을 합칠 수 있게 되었다.

이것을 '멀티 catch 블럭'이라고 한다. 

 

멀티 catch 블럭을 사용하게 되면 중복된 코드를 줄일 수 있다는 장점이 있다.

또한 멀티 catch블럭은 서로서로 내용이 같아야 한다.

 

 

'|' 기호로 연결할 수 있는 예외 클래스의 개수는 제한이 없다.

멀티 catch블럭안에 참조 변수는 단 하나

 

🔑 멀티 catch문을 사용한 코드와 아닌 코드


import static java.lang.System.out;
public class Exceptiontest {

	public static void main(String[] args) {
		
		try{
			out.println(0/0);
		}catch(ArithmeticException ae) {
			out.println(ae.getMessage());
		}catch(ArrayIndexOutOfBoundsException abe) {
			out.println(abe.getMessage());
		}
		
	}

}

멀티 catch 사용 안함!

 

import static java.lang.System.out;
public class Exceptiontest {

	public static void main(String[] args) {
		
		try{
			out.println(0/0);
		}catch(ArithmeticException  | ArrayIndexOutOfBoundsException abe) {
			out.println(abe.getMessage());
		}
		
	}

}

멀티 catch 사용함!

 

코드의 중복과 가독성이 좋아졌다.

 

 


 

 

📣 멀티 catch 주의사항

 

 

1.  멀티 catch블럭에 사용되는 두 클래스가 부모 자식 관계이면 사용할 수 없다.

이유는 부모 클래스는 자식의 기준과 같기 때문이다. 자식이 부모로부터 상속받았기 때문, 굳이 멀티 catch로 사용할 필요가 없어지는 것이다.

		try{
			out.println(0/0);
		}catch(ArrayIndexOutOfBoundsException |Exception e) {
			
		}

위 코드는 주의사항 1번에 성립하기 때문에 예외가 발생한다.   ArraysIndexOutOfException은 Exception의 자식이다. 부모 자식 관계이므로 예외 발생

 

 

 

2. 하나의 Exception에만 존재하는 멤버 메서드를 사용하면 안 된다. 

멀티 catch블럭 내에서는 실제로 어떤 예외가 발생했는지 알 수 없다. 그래서 멀티 catch블럭 참조 변수로 '|' 로 연결된 예외들의 공통분모의 조상 예외 클래스에 선언된 멤버만 사용할 수 있다.

 

 

정 사용해야 된다면,

 

조건문을 이용해 instanceof연산을 한 후

멀티 catch블록 참조 변수를 instanceof로 체크한 예외 클래스로 형변환 한다.

 

이런 식으로 할빠엔 따로 catch블럭을 만드는 게 더 실용적이다.

 

 


 

📖 예외 발생시키기

 

키워드 throw를 사용하여 프로그래머가 고의적으로 예외를 발생시킬 수 있다.

 

 

순서

1. 연산자 new를 이용해 발생시키려는 예외 클래스 객체 생성. (인스턴스화)
2. 키워드 throw를 이용해서 예외 던지기.

 

 

public class Exceptiontest {

	public static void main(String[] args) {
		try{
			ArrayIndexOutOfBoundsException a1=new ArrayIndexOutOfBoundsException("!고의 발생!");
			throw a1;
		}catch(ArrayIndexOutOfBoundsException a2) {
			if(a2 instanceof ArrayIndexOutOfBoundsException) {
				System.out.println("catch구동  "+a2.getMessage());
				a2.printStackTrace();
			}
		}
		System.out.println("종료");
	}
}

출력결과

 

 

ArrayIndexOutOfBoundsException 객체를 생성할 때 소괄호 안에 문자열을 넣어주면 

getMessage()나 printStackTrace()등 Exception 메서드를 호출하면 문자열로 넣어준 데이터가 사용된다.

 

알아야 할 점은, 객체를 생성한다. throw로 참조변수를 던진다.

 

public class Exceptiontest {

	public static void main(String[] args) {
		try {
			throw new ArithmeticException("!고의!");
		}catch(ArithmeticException a) {
			a.printStackTrace();
		}
		System.out.println("종료");
		
	}

}

 

throw new 예외 발생시킬 클래스() 이런 식으로 줄여 쓸 수 도 있다.  (이때는 참조 변수 사용 안 함)

 


 

📖 checked 예외, unchecked 예외

 

checked예외: 컴파일러가 예외처리 여부를 체크  (예외 처리 필수)

Exception 예외와 그 자손은 try&catch 필수 Exception=checked

 

unchecked예외: 컴파일러가 예외 처리 여부를 체크 안 함 (예외 처리 선택)

RuntimeException과 그 자손은 try&catch 선택  RuntimeException=unchecked

 

 

 

checked예외 예

public class Exceptiontest {

	public static void main(String[] args) {
		throw new Exception();
	}

}

 

에러가 발생한다.

컴파일조차 불가능 try&catch문을 사용하면 컴파일 가능

 

 

 

 

 

unchecked 예외 예

public static void main(String[] args) {
		throw new ArrayIndexOutOfBoundsException();
	}

에러 발생이 안된다.

예외는 발생.

 

 

 

결론   Exception 클래스와 그 자손들 예외처리 필수 (checked)

         RuntmeException 클래스와 그 자손들은 선택  (unchecked)

 

 

 

 

 

 

RuntimeException도 예외처리를 필수적으로 하면 거의 모든 코드에 try&catch를 사용해야 하기 때문이다.

 


 

 

 

 

 

 

 

 

 

🚀 다음 글 보기 (예외처리 1-4)



 

 

 

 

🚀 이전 글 보기 (예외처리 1-2)



 

 

 

 

 

 

커버 사진

https://kr.freepik.com/free-icon/java_14029802.htm

<div>Icons made by <a href="https://www.freepik.com" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div>