try ~catch 에러 잡기

try ~catch 에러 잡기

오류 확인하는 try ~catch문

public static void main(String[] args) { //사용자의 입력값을 가정 String[] src = {"가","2","aaa","ccc"}; //src의 내용들을 숫자로 변환해서 저장할 배열 int[] arr = new int[3]; try { for (int i = 0; i < src.length; i++) { arr[i]=Integer.parseInt(src[i]); System.out.println(arr[i]); }} catch(NumberFormatException e) { System.out.println("입력값에 오류가 있습니다."); //개발자가 보려는 용도로 출력하는 시스템 에러 메시지 e.printStackTrace(); } System.out.println("-------프로그램종료============="); } }

결과 값으로

더보기 입력값에 오류가 있습니다.

java.lang.NumberFormatException: For input string: "가"

-------프로그램종료=============

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at day17.Main06.main(Main06.java:14)

이번에는 다른 예시로

public class Main06 { public static void main(String[] args) { //사용자의 입력값을 가정 String[] src = {"1","2","3","4"}; //src의 내용들을 숫자로 변환해서 저장할 배열 int[] arr = new int[3]; try { for (int i = 0; i < src.length; i++) { arr[i]=Integer.parseInt(src[i]); System.out.println(arr[i]); }} catch(NumberFormatException e) { System.out.println("입력값에 오류가 있습니다."); //개발자가 보려는 용도로 출력하는 시스템 에러 메시지 e.printStackTrace(); }catch(IndexOutOfBoundsException e) { System.out.println("데이터가 너무 많습니다."); e.printStackTrace(); } System.out.println("-------프로그램종료============="); } }

src에 1,2,3,4 로 변경시켜준뒤에

이번에는 다 담가지 않아 데이터가 너무 많다고 나올 수 있도록 새로운 catch문을 만들어 준다.

결과 값으로.

더보기 1

2

3

데이터가 너무 많습니다.

-------프로그램종료=============

java.lang.ArrayIndexOutOfBoundsException: 3

at day17.Main06.main(Main06.java:14)

마지막 총! 완!성!본

public class Main06 { public static void main(String[] args) { //사용자의 입력값을 가정 String[] src = {"1","2","3"}; //src의 내용들을 숫자로 변환해서 저장할 배열 int[] arr = new int[3]; try { for (int i = 0; i < src.length; i++) { arr[i]=Integer.parseInt(src[i]); System.out.println(arr[i]); }} catch(NumberFormatException e) { System.out.println("입력값에 오류가 있습니다."); //개발자가 보려는 용도로 출력하는 시스템 에러 메시지 e.printStackTrace(); }catch(IndexOutOfBoundsException e) { System.out.println("데이터가 너무 많습니다."); e.printStackTrace(); }catch(Exception e) { /* * 예외 종류를 의미하는 모든 클래스는 * java.lang.Exception 클래스를 상속 받으므로, * 이 블록은 모두 종류의 예외에 대처할 수 있다. * */ System.out.println("알 수 없는 예외가 발생했습니다."); e.printStackTrace(); }finally { //이 블록은 예외의 발생 여부에 상관없이 무조건 실행된다. System.out.println("데이터 변환 종료!"); } System.out.println("-------프로그램종료============="); } }

from http://burger-it.tistory.com/10 by ccl(A) rewrite - 2021-10-22 16:27:26