Exception 예외 처리

박성현·2024년 3월 25일

java

목록 보기
40/51

예외 처리 try~catch(Exception)

문제생기는 부분으로 인해 작업이 끊기게 하지 않고 에러부분을 확인할 수 있도록 해주는 이점이 있다

부모님의 이름으로 자식을 받을 수 있게 하는 것이 다형성이고 다형성이 있기 때문에 Exception e로 인자값을 받아 e.printStackTrace();해보면 에러메세지를 받을 수 있다.

ArithmeticException e와 같은 시스템 함수는 자바스크립트에서의 콜백함수와 같다.


ArithmeticException e

  • 정수 나눗셈에서 나누는 수가 0인 경우
  • 부동 소수점 수의 나눗셈에서 0으로 나누는 경우
  • 정수형 값을 부동소수점 수로 형변환을 할 때 범위를 벗어나는 경우
package exceptionpkg;

public class ExceptionEx05 {

	public static void main(String[] args) {
		System.out.println(1);
		System.out.println(2);
		try {
			System.out.println(3);
			System.out.println(3/0); // 에러가 뜨는 순간 catch문으로 넘어가게됨
			System.out.println(4);
		} catch (ArithmeticException ae) {
			System.out.println("ArithmeticException");
		} catch (NullPointerException e) {
			System.out.println("NullPointerException");
		} catch (Exception e) {
			//	아래로 결과값을 받아볼 수 있음
			System.out.println(e.getMessage());
			e.printStackTrace();
		// 예외 발생 여부와 상관없이 수행
		}finally {
			System.out.println("end");
		}
	}

}

결과값 :


throws 예약어

  • 예외 처리는 원래 예외가 발생한 메서드 안에서 처리 하는 것이 기본
  • 예외 처리를 자신을 호출 한 메서드에서 처리
package exceptionpkg;

public class ExceptionEx06 {
	
	// throws로 에러를 직접받아서 처리할 수 있음
	public void exceptionMethod() throws Exception {
		throw new Exception();
	}
	
	
	public static void main(String[] args) {
		ExceptionEx06 ex6 = new ExceptionEx06();
		try {
			ex6.exceptionMethod();
		} catch (Exception e) {
			// 매개변수로 받은 e갑으로 오류 메세지를 받음
			e.printStackTrace();
		}
	}

}

결과값 :


try, catch를 이용해 아이디 비밀번호 입력받아 맞는지 여부 판단하기

package exceptionpkg;

import java.util.Scanner;

public class LoginExceptionMain {

	static final String USER_ID = "park";
	static final String USER_PW = "1234";

	public static void main(String[] args)  {
		Scanner sc= new Scanner(System.in);
		try {

			System.out.println("ID > ");
			String inputId= sc.next();
			System.out.println("PW > ");
			String inputPW= sc.next();

			if(!USER_ID.equals(inputId)) {
				throw new LoginException("아이디가 틀립니다.");
			}else if (!USER_PW.equals(inputPW)) {
				throw new LoginException("비밀번호가 틀립니다.");
			}
		}catch (Exception e) {
			e.printStackTrace();
		} 
	}

}

결과값 :

profile
개발기록장

0개의 댓글