본문 바로가기
Java

예외처리 (Exception) - throw , throws , trycatch

by 임혁진 2023. 11. 23.

예외가 발생하면  문제가 발생한 곳에 대한 정보 출력과 프로그램이 종료된다.

예외처리

- 에러에 대한 처리를 의미한다.

- 자바는 예외처리 메커니즘을 제공한다.

- 프로그램에서 문제가 될만한 부분을 예상하여 사전에 "문제가 발생하면 이렇게 처리하라" 라고

   프로그래밍 하는 것을 예외 처리라고 합니다

 

주요 실행 예외

1.NullPointerException 

-객체 참조가 없는 상태, 즉 null 값을 갖는 참조 변수로 객체 접근 연산자인 dot(.)를 사용했을 때 발생 합니다.

2.ArrayIndexOutOfBoundsException

- 배열에서 인덱스 범위를 초과하여 사용할 경우 발생합니다.

3.NumberFormatException

- 문자열로 되어 있는 데이터를 숫자로 변경하는 경우에 발생합니다

4.ClassCastException

- 형 변환은 부모 클래스와 자식 클래스간에 발생하고 구현 클래스와 인터페이스 간에도 발생합니다. 이 러한 관계가 아니라면 다른 클래스로 타입을 변환할 수 없습니다.

 

예외처리 방법1 (try~catch~finally)

1. try - try 블록에는 예외 발생 가능성이 있는 코드를 작성

2. try 내부에서 예외가 발생하면 즉시 실행을 멈추고 catch 블록으로 이동

 

PS. 항상 실행할 내용이 있다면 finally 블록에 

 

* 주의할 점 상위 예외 클래스가 하위 예외 클래스보다 아래쪽에 위치해야 한다.(예외도 상속)

public class TryCatchEx01 {

 

public static void main(String[] args) {

 

int x = 10;

int y = 0;

try {

 

System.out.println(x + y);

 

System.out.println(x / y);

 

System.out.println(x * y);

 

 

} catch (Exception e) {

System.out.println("0으로 나누지 마세요!");

}

}

}

public class TrycatchEx02 {

 

public static void main(String[] args) {

 

String[] arr = {"홍길동", "이순신", "피카츄"};

 

 

int i = 0;

while(i < 4) {

 

try {

System.out.println(arr[i]);

 

} catch (Exception e) {

System.out.println("배열 범위를 벗어났습니다");

} finally {

System.out.println("이 문장은 예외 여부와 상관없이 무조건 실행됩니다");

}

 

i++;

}

 

System.out.println("프로그램 정상종료");

}

}

public class RuntimeEx {

 

public static void main(String[] args) {

 

//Nullpointer

// String str = null;

// str.charAt(0);

//ArrayIndexOut

// int[] arr = {1,2,3 };

// arr[4] = 100;

 

//ClassCast

//String str = (String)new Object();

 

//NumberFormat

int result = Integer.parseInt("hello world");

}

}

런타임에러

catch 문 여러개 쓰기

public class MultiTrycatchEx01 {

 

public static void main(String[] args) {

 

/*

* 참고로만 알아두기

*

* main도 매개변수를 받을 수 있습니다.

*

* Run -> Run configration -> arguement -> ${string_prompt}

*/

 

//1. 이 값을 숫자로 변경하고

//2. 두 수의 합을 구한다

 

try {

 

String a1 = args[0];

String a2 = args[1];

 

int a = Integer.parseInt(a1); //문자열을 숫자로 변경하는 기능

int b = Integer.parseInt(a2);

 

System.out.println("두 수의 합:" + (a + b) );

 

String str = null;

str.charAt(0);

 

} catch (ArrayIndexOutOfBoundsException e) { //처리할 예외의 종류가 들어갑니다

System.out.println("반드시 매개값을 2개 넣어주세요");

} catch (NumberFormatException | NullPointerException e ) {

System.out.println("매개값을 숫자로 입력하세요");

} catch (Exception e) {

System.out.println("기타 예외 입니다");

}

}

}

 

Throws (예외 떠넘기기)

public class ThrowsEx01 {

 

public static void main(String[] args) {

 

/*

* 메서드 or 생성자에 발생되는 예외를 떠넘기는 키워드가 throws 입니다

*

* throws가 붙은 메서드, 생성자를 호출할 때는 예외처리를 대신 진행해야 합니다.

*

* 즉, 메서드or생성자 에서 예외처리를 강요하고 싶을 때 사용될 수 있습니다.

*/

 

try {

greeting(3);

} catch (Exception e) {

System.out.println("예외가 발생했습니다. 0~2사이 값을 넣어주세요");

}

 

//throws가 적용된 메서드 예시

try {

Class.forName("@#$@#$");

 

} catch (Exception e) {

System.out.println("해당 클래스가 없습니다");

}

 

//throws가 적용된 생성자 예시

try {

new FileInputStream("%#$%");

 

} catch (Exception e) {

System.out.println("해당 파일이 없습니다");

}

}

 

public static String[] arr = {"안녕하세요", "hello", "고니찌와"};

public static void greeting(int index) throws Exception {

 

System.out.println(index + "번째 인사법입니다");

System.out.println(arr[index] );

}

}

public class ThrowsEx02 {

 

public ThrowsEx02() throws Exception {

System.out.println("생성자 호출");

aaa();

System.out.println("생성자 종료");

}

 

public void aaa() throws Exception {

System.out.println("aaa시작");

bbb();

System.out.println("aaa종료");

}

 

public void bbb() throws Exception {

System.out.println("bbb시작");

 

System.out.println(10 / 0); //exception

 

System.out.println("bbb종료");

}

 

}

에러가 메소드 실행한 곳에서 뜬다

 

Throw - 예외 강제로 발생시키기

public static void main(String[] args) {

 

/*

* throw - 예외 강제로 발생시키기

*

* 메서드나 생성자에서 throw new 예외클래스()

* 를 만나면 예외가 생성됩니다.

*

* throw키워드를 만나면

* try~catch 문장이나 throws키워드로 예외처리를 진행해야 합니다.

*

* throw특정 조건과 함께 catch문장으로 프로그램 실행을 옮길 때 사용가능합니다.

*/

try {

 

int result = calc(-10);

System.out.println(result);

 

} catch (Exception e) {

//System.out.println( e.getMessage() ); //예외 발생시 예외객체가 가지고 있는 메시지를 얻는 기능

e.printStackTrace();

//예외 경로를 추적하는 메시지를 출력하는 용도로 많이 사용됩니다.

//예외 원인을 찾을 때, 개발시에 매번 사용됩니다.

}

 

System.out.println("프로그램 정상종료");

}

 

public static int calc(int n) throws Exception {

 

//음수가 넘어오면 메서드 실행할 필요도 없이 강제종료

if(n < 0) {

throw new Exception("값을 양수로 전달하세요");

}

 

 

int sum = 0;

for(int i = 1; i <= n; i++) {

sum += i;

}

 

return sum;

}

}

e.printStackTrace(); < 예외 원인 찾기

 

예외 강제 발생 - throw new Exception();

 

 

사용자 정의 예외

=> 자바 표준 api 제공 예외 가 아닌 다양한 종류의 예외를 표현 하기 위

=> Exception 클래스를 상속하여 사용