Exception이란
두개의 경우로 나뉘어 진다.
- Error
- Excpetion
ctrl + 마우스 오버
여기서 Implementation으로 들어가 보면 해당 객체로 갈 수 있다.
그 후 해당 객체에 마우스를 가져다 대고 잠시 기다리면 설명글들을 읽을 수 있다.
Error는 말 그대로 심각한 문제.
그 뒷줄에 보면 should not try to catch라고 적혀있다. 말 그대로 Error는 따로 처리하려 하지 말라는말.
Exception의 경우 might want to catch.
해결할 수 있다.
Exception의 경우 두가지의 경우가 있다.
직계와 runtimeexcption
runtimeException, (unchecked exception)
Exception의 직계들인 checekd exception이 있다.(SQLException, IOException)
throws와 throw
throws의 경우 checked exception이 호출자에게 예외처리를 떠넘길 때 쓰는것.
throw의 경우 새로운 강제적인 오류를 발생시킬때 쓴다.
main에서 사용하기 때문에 main에 throws를 쓰면 VM(버츄얼머신)에게 예외처리가 넘어가게 된다.
실행 해 보면 vm이 해당 예외를 처리함.
직접 예외를 처리해 보자.
*checked와 unchecked 오류의 차이점.
- unchecked exception 의 경우 throws를 따로 해 주지 않더라도 알아서 넘어간다.
- checked의 경우 호출자에게 넘기려면 throws를 반드시 적어주어야함.
- check의 경우 throws를 쓰지 않는다면 compile 오류가 발생한다.
예외를 따로 throws 를 주지 않더라도 계속 호출자를 타고갈 수 있다면
uunched
throws를 주지 않으면 컴파일에러가 발생하면
chedcked
메서드의 시그니쳐를 따로 건드리지 않고(throws 쓰지 않고) checked exception을 호출자에게 넘기기
checked를 unchecked로 넘겨주면 된다.
custom exception 생성하기
생성할 때 우선 unchecked Exception을 만들어야할지 checked Exception을 만들어야할지
정해서 extends를 정하면 된다.
Exception에 대한 정리
package kr.or.ddit.exception; import java.io.IOException; import java.sql.SQLException; /** * 예외(Throwable) : 실행과정에서 발생하는 모든 비정상 상황 * - Error : 개발자가 처리하지 않고, VM이 제어권을 넘겨받는 예외의 한 종류(fatal error). * - Exception : 개발자가 처리할 수 있는 예외 * - checked exception : Exception 의 직계 * : 예외 발생 가능한 코드가 있으면, 반드시 처리를 해야하는 예외 * SQLException, IOException, SocketException * - unchecked exception : RuntimeException 직계 * : 명시적으로 처리하지 않더라도 호출자 혹은 VM에게 제어권이 전달되는 예외 * NullpointerException, IllegalArgumentException * * * * ** 예외 처리 방법 * 1. 직접 처리 * try(closable 객체 생성){ * 예의 발생 가능 코드 * } ~ catch(captuable exception){ * 예외 처리 코드 * }~ finally{ * 예외 발생 여부와 무관하게 처리할 코드 * } * 2. 호출자에게 위임하는 처리 : throws * * ** 예외 발생 방법 * throw new 예외 객체 생성 * (throw가 없다면 그냥 일반 객체.) * * * ** custom 예외 정의 방법 * : 상위(예외의 특성에 따라 Exception/RuntimeException)의 예외 클래스를 상속 * 처리하고 싶다면 exception 처리하지 못한다고 판단하면 runtime * un or checked부터 정하자. * */ public class ExceptionDesc { public static void main(String[] args){ // try { // String retValue = method1(); // System.out.println(retValue); // } catch (IOException e) { // e.printStackTrace(); //// throw e; catch 밖에 녀석이 실행되지 않는다. 그리고 throws를 해줘얗마. // } try { System.out.println(method2()); }catch(RuntimeException e) { System.err.println(e.getMessage()); throw e; } } private static String method2(){ try { if(1==1)// uncheced // throw new IllegalArgumentException("강제발생예외"); throw new SQLException("강제발생예외"); return "method2RetValue"; }catch(SQLException e) { // customexception으로 해서 db쪽에서만 예외가 발생햇다는 것을 // 쉽게 알아챌 수 있다. throw new DataAccessException(e); } } private static String method1() throws IOException { try { if(1==1) { // new IOException("강제 발생 예외"); throw new IOException("강제 발생 예외"); } return "method1RetValue"; }catch(IOException e) { System.err.println("예외 발생했음."+e.getMessage()); throw e; } } }
간단한 변경.
500error(tomcat)이 서버에서 오류가 났다고 판단한 것을 400으로 바꿔보기
이렇게 try catch로 묶어서 catch 부분에 처리해 주면 된다.
500 → 400 → 500에러로 변경해주기
package kr.or.ddit.member.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import kr.or.ddit.enumpkg.ServiceResult; import kr.or.ddit.member.UserNotFoundException; import kr.or.ddit.service.AuthenticateServiceImpl; import kr.or.ddit.service.IAuthenticateService; import kr.or.ddit.service.IMemberService; import kr.or.ddit.service.MemberServiceImpl; import kr.or.ddit.vo.MemberVO; @WebServlet("/mypage.do") public class MypageServlet_sam extends HttpServlet{ private IMemberService service = new MemberServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); MemberVO authMember = (MemberVO) session.getAttribute("authMember"); String mem_id = authMember.getMem_id(); try { MemberVO detailMember = service.retrieveMember(mem_id); req.setAttribute("member", detailMember); String view = "/WEB-INF/views/member/mypage.jsp"; req.getRequestDispatcher(view).forward(req, resp); } catch (UserNotFoundException e) { // resp.sendError(400); // 500으로 다시 바꿔보기 throw new IOException(e); } } }
Uploaded by Notion2Tistory v1.1.0