본문 바로가기

Java&JSP&Spring/Java

[JAVA]자바의 예외처리(Exception) 정리 (2)

[JAVA]자바의 예외처리(Exception) 정리 (2)

저번 포스팅에서는 예외처리의 기본 개념에 대해서 간단하게 정리해보았는데요

 

[JAVA]자바의 예외처리(Exception) 정리 (1)

[JAVA]자바의 예외처리(Exception) 정리 (1) 이번 포스팅에서는 자바의 예외처리를 활용하는 방법에 대해서 정리해보려고 합니다. 예외(Exception)와 에러(Error)의 차이점 예외처리와 에러를 보통 에러

nameybs.tistory.com

이번 포스팅에서는 실제로 Exception을 만들어서 활용해보는 시간을 가져보려고 합니다.

 

사용자 예외 클래스 작성

기본적으로 제공되어지는 예외 말고 유저가 임의로 예외 클래스를 작성 할 수 있습니다.

사용자 예외 클래스

사용자 예외 클래스에는 임의로 주어지는 에러 코드와

예외 발생시 취득이 필요한 클래스를 각각 필드에 선언 하였습니다.

package com.test;

public class MyException extends RuntimeException {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	// 에러코드
	private Integer errCode;
	// 학생 클래스
	private Student student;
	
	public MyException() {
		// Default에러코드
		this.errCode = 100;
	}
	
	public MyException(Integer errCode) {
		this.errCode = errCode;
	}
	
	public MyException(Integer errCode, Student student) {
		this.errCode = errCode;
		this.student = student;
	}
	
	public MyException(String msg) {
		super(msg);
		// Default에러코드
		this.errCode = 100;
	}
	
	public MyException(String msg, Integer errCode) {
		super(msg);
		this.errCode = errCode;
	}

	public MyException(String msg, Integer errCode, Student student) {
		this(msg, errCode);
		this.student = student;
	}
	
	// 에러코드 취득
	public Integer getErrCode() {
		return this.errCode;
	}
	
	// 학생 클래스 취득
	public Student getStudent() {
		return this.student;
	}
}

학생 클래스

예외 페이지 검증을 위해 임시로 제작한 클래스입니다.

package com.test;

public class Student {

	private String name;
	private String sClass;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getsClass() {
		return sClass;
	}
	public void setsClass(String sClass) {
		this.sClass = sClass;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

메인 클래스

위에서 작성한 예외를 메인클래스에서 적용 하고 있습니다.

RuntimeException을 상속받고 있기 때문에 checkAge메소드에 throws MyException을 선언 해주지 않아도 에러가 나지 않습니다.(Exception을 상속받고 있을 경우에는 명시가 필요함)

또한 메인 메소드의 catch에서 예외 클래스에서 가지고 있던 student클래스의 정보를 취득해서 볼 수 있습니다.

package com.test;

import java.util.ArrayList;
import java.util.List;

public class MainClass {
	public static void main(String[] args) {
		
		// 학생 정보 추가
		List<Student> students = new ArrayList<Student>();
		Student std = new Student();
		std.setName("Tom");
		std.setsClass("1");
		std.setAge(10);
		students.add(std);
		
		std = new Student();
		std.setName("Jack");
		std.setsClass("2");
		std.setAge(10);
		students.add(std);
		
		std = new Student();
		std.setName("Peter");
		std.setsClass("3");
		std.setAge(12);
		students.add(std);
		
		try {
			for (int i = 0; i < students.size(); i++) {
				// 학급 체크
				checkClass(students.get(i));
				// 나이 체크
				checkAge(students.get(i));
			}
		} catch (MyException e) {
			System.err.println(e.getMessage() +  " 에러코드 = " + e.getErrCode());
			e.printStackTrace();
			System.out.println("StudentName : " + e.getStudent().getName());
		}
	}
	
	/**
	 * 학급 체크 (3반일 경우에 예외 처리)
	 * @param std
	 * @throws MyException
	 */
	public static void checkClass(Student std) throws MyException {
		if("3".equals(std.getsClass())) {
			throw new MyException("해당 학급 클래스는 존재하지 않습니다.", 300, std);
		}
	}
	
	/**
	 * 나이 체크 (10세 이상일 경우 예외 처리)
	 * @param std
	 */
	public static void checkAge(Student std) {
		if(std.getAge() > 10) {
			throw new MyException("최저 나이 조건을 충족하지 않았습니다.", 200, std);
		}
	}
}

처리 결과

해당 학급 클래스는 존재하지 않습니다. 에러코드 = 300
com.test.MyException: 해당 학급 클래스는 존재하지 않습니다.
at com.test.MainClass.checkClass(MainClass.java:50)
at com.test.MainClass.main(MainClass.java:32)
StudentName : Peter

샘플 프로젝트를 첨부합니다.

Exception.zip
0.00MB

728x90
반응형