Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

David의 블로그

[JSP/Servlet]Custom Exception 만들어보기 본문

프로그래밍/Jsp_Servlet

[JSP/Servlet]Custom Exception 만들어보기

David 리 2023. 11. 26. 00:35

자바 혹은 JSP 웹 프로그래밍을 공부하거나 프로젝트를 하면서

많은 Exception을 접하곤한다.

특히나 개발을 하다보면 100% 완벽한 코딩은 없기에 버그나 오류를 접하는게 당연하다고 생각한다.

 

이번에는 custom Exception을 만들어보면서

유효성 체크 로직이나 필수값 입력 로직 Exception처리의 감을 잡을 수 있었다.

 

custom Exception연습은

eclipse 다이나믹 프로젝트로 연습을 해 보았다.

프로젝트 패키지의 구조는 위의 이미지와 같다.

 

 

[web.xml]

나는 web.xml에 <servlet>태그를 선언하고 <url-pattern>으로 모든 매핑 요청을 mainServlet클래스로 받게 끔 처리했다.

 

 

[CustomException]

CustomException 클래스인데  RuntimeException 클래스를 상속받고

메시지를 뿌리게 끔 설정해 놓았다.

1
2
3
4
5
6
7
8
9
10
package exception;
 
public class CustomException extends RuntimeException{
    
    public CustomException(String message) {
        super(message);
    }
 
}
 
cs

 

[CustomFormatException]

또 하나의 CustomFormatException 클래스도 설정이 같다.

1
2
3
4
5
6
7
8
9
10
package exception;
 
public class CustomFormatException extends RuntimeException{
 
    public CustomFormatException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }
}
 
cs

 

 

[MainServlet]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package exception;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class mainServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        resp.setContentType("text/html; charset=utf-8");
 
        PrintWriter out = resp.getWriter();
        
        int a = 1;
        int b = 0;
 
        // 커스텀 Exception 만들기
        try {
            
            // 파라미터로 넘어온 no와 a를 비교해서 같지 않으면 CustomException처리 할거임.
            String c = req.getParameter("no");
            test(Integer.parseInt(c), a);
            
            out.println("<html>");
            out.println("<head><title>현재시간</title></head>");
            out.println("<body>");
            out.println("나눈 결과는?");
            out.println(050/0);
            out.println("입니다.");
            out.println("</body></html>");
            
        } 
//        catch (ArithmeticException e) {
//            e.getMessage();
//        } 
        catch (CustomFormatException e) {
            throw new CustomFormatException("String not format number");
        }
        catch (NumberFormatException e) {
            throw new CustomFormatException("String not format number");
        }
    }
 
    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        super.init();
    }
    
    private void test(int a, int b) {
        if (a != b) {
            throw new CustomException("A and B equals not Int");
        }
    }
}
 
cs

27 ~ 28Line 

HttpServletReqeust 객체로 넘어온 'no'의 값과 

int형 a변수와 값을 비교한다.

값이 같지 않으면 56Line에서 CustomException을 발생시킨다

45 ~ 47Line

HttpServletReqeust 객체로 넘어온 'no'의 값이 숫자가 아닌 문자열

들어온다면 발생한다.

 

 

 

이제 실행을 해보겠다.

CustomException이 발생한 결과이다.

 

CustomFormatException이 발생한 화면이다.

[소감 및 마무리]

나는 Exception처리를 단순하게 try ~ catch문안에서

catch부분에다가 Exception만을 설정했다.

 

하지만 개발자 입장에서 

Exception처리를 포괄적으로 한다면

어느 부분에서 오류가 났는지 파악하기가 쉽지 않을것이다.

결과적으로 개발 속도에 악영향을 끼칠것이 분명하다.

 

이번에 공부를했으니

앞으로 Exception처리를 하는 습관을 들여야겠다.

 

다음에는 실제 웹프로그래밍 환경에서

에러처리를 어떻게 하는지 공부를 해봐야겠다.

https://78alswo.tistory.com/11

 

[JSP/Servlet] Custom Error페이지 만들기1

전에는 CustomException하는 방법을 공부 해 봤다. 이번시간은 실무에서 에러코드, 익셉션 타입에 맞게 에러페이지를 작성해 보도록 하겠다. 실제 실무에서는 에러가 나면 톰캣(WAS)에서 보여주는 화

78alswo.tistory.com