JAVA Exception 예외 처리

JAVA Exception 예외 처리

728x90

JAVA Exception 예외 처리

예외 : 프로그램 실행 중 예기치 못한 비정상적인 상황

예외가 나타나게 방치 후 사후 처리를 한다.

try~ catch 문에 의해 직접 처리하고, 메서드 호출 측으로 throws를 명시적으로 써준다.

Unchecked Exception : RuntimeException 예외처리 선택

ArithmeticException : 0으로 나누는 경우, 논리 적 예외

ArrayIndexOutOfBoundsException : 잘못된 배열 첨자 예외

NegativeArraySizeException : 배열 선언 시 할당 크기가 음수일 때 예외

ClassCastException : 허용 불가능한 형 변환 예외

NullPointerException : null 값을 갖는 참조 변수로 멤버 접근 예외

NumberFormatException : wrapper 클래스의 parse 메서드로 문자열-> 숫자 자료형 예외

java.util.InputMismatchException : Scanner 클래스의 next 메서드 받는 자료형 예외

java.io.IOException : 입출력 동작 예외

기타

String getMessage() : 예외 객체가 가지고 있는 에러 메시지 반환

void printStackTrace() : 예외 발생 원인과 경로를 추적하여 콘솔에 표시, 디버깅 목적

<오류 객체에서 메시지 받아오기>

public class Exception{ public static void main(String[] args){ int num1 = 3, num2 = 0; try{ int result = num1/num2; System.out.println(result); } catch(ArithmeticException ae){ String str = ae.getMessage(); // 오류 객체에서 메세지를 받아옴 System.err.println(str); } System.out.println("끝"); } }

<메서드에서 예외가 생기면 던지기>

public class Exception2{ static int divide(int a, int b) throws ArithmeticException{ int result = a/b; return result; } public static void main(String[] args){ try{ int result = devide(3,0); System.out.println(result); // 예외가 없다면 출력 } catch(ArithmeticException ae){ String str = ae.getMessage(); // 예외 메세지 가지고 옴 System.out.println(str); } System.out.println("끝"); } }

public class NextIntException{ static int getInteger() throws InputMismatchException{ Scanner s = new Scanner(System.in); int num = s.nextInt(); return num; } public static void main(String[] args){ boolean exception = true; for(;exception;){ // 제대로 입력할때까지 반복 System.out.print("정수를 입력하시오 : "); try{ int result = getInteger(); System.out.println("입력한 값 : " + result); exception = false; } catch(InputMismatchException im){ String str = im.getMessage(); // 예외 메세지 가지고오기 System.err.println(str); System.out.println("다시 입력하세요"); } } } }

728x90

from http://psy-er.tistory.com/92 by ccl(A) rewrite - 2021-12-03 13:02:15