예외처리 EXCEPTION

2022. 3. 7. 16:36·Programing/JAVA
  • 오류 : 에러 Error와 예외 Exception
  • 에러 : 프로그램 코드에서 해결 할 수 없는 심각한 오류( JVM 오류, 메모리 부족등)
  • 예외 : 프로그램 코드에 의해 처리할 수 있는 오류

예외 클래스

  • Exception

이미지참조:https://ccm3.net/archives/20672

예외 처리 try~catch(Exception)

/ by zero 오류 발생

class ExceptionEx02 {
    public static void main(String args[]) {
        int number = 100;
        int result = 0;

        for(int i=0; i < 10; i++) {
            result = number / (int)(Math.random() * 10); // 7번째 라인
            System.out.println(result);
        }
    } // main의 끝
}

예외처리

class ExceptionEx03 {
    public static void main(String args[]) {
        int number = 100;
        int result = 0;

        for(int i=0; i < 10; i++) {
            try {
                result = number / (int)(Math.random() * 10);
                System.out.println(result);
            } catch (ArithmeticException e) {
                System.out.println("0");    
            } // try-catch의 끝
        } // for의 끝
    } 
}

try-catch 문에서의 흐름

  • try 블럭 내에서 예외 발생시 예외와 일치 하는 catch 블럭 찾기
  • 찾으면 catch 블럭 수행 후 catch 블럭 빠저 나감
class ExceptionEx05 {
    public static void main(String args[]) {
            System.out.println(1);          
            System.out.println(2);
            try {
                System.out.println(3);
                System.out.println(0/0);    
                System.out.println(4);  // 실행되지 않는다.
            } catch (ArithmeticException ae)    {
                System.out.println(5);
            }   // try-catch의 끝
            System.out.println(6);
    }   // main메서드의 끝
}
  • catch 블럭이 여러개 일 경우 처음 일치하는 catch 블럭 만 수행 함
class ExceptionEx07 {
    public static void main(String args[]) {
        System.out.println(1);          
        System.out.println(2);
        try {
            System.out.println(3);
            System.out.println(0/0);
            System.out.println(4);      // 실행되지 않는다.
        } catch (ArithmeticException ae)    {
            if (ae instanceof ArithmeticException) 
                System.out.println("true"); 
            System.out.println("ArithmeticException");
        } catch (Exception e)   {
            System.out.println("Exception");
        }   // try-catch의 끝
        System.out.println(6);
    }   // main메서드의 끝
}

printStackTrace() 와 getMessage()

  • printStackTrace() : 예외발생 당시의 호출스택에 있었던 메서드 정보와 예외메세지 화면에 출력
  • getMessage(): 발생한 예외클래시의 인스턴스에 저장된 메세지를 얻을 수 있다
class ExceptionEx08 {
    public static void main(String args[]) {
        System.out.println(1);          
        System.out.println(2);
        try {
            System.out.println(3);
            System.out.println(0/0); // 예외발생!!!
            System.out.println(4);   // 실행되지 않는다.
        } catch (ArithmeticException ae)    {
            ae.printStackTrace();
            System.out.println("예외메시지 : " + ae.getMessage());
        }   // try-catch의 끝
        System.out.println(6);
    }   // main메서드의 끝
}

finally 블럭

  • try-catch 문과 함께 예외 발생여부에 상관없이 실행되어야 할 코드 작성
try{
    // 예외가 발생할 가능성이 있는 문장
} catch (Exception e) {
    // 예외 처리를 위한 문장
} finally {
    예외 발생 여부와 상관 없이 수행
}

throws 예약어

  • 예외 처리는 원래 예외가 발생한 메서드 안에서 처리 하는 것이 기본
  • 예외 처리를 자신을 호출 한 메서드에서 처리
public class ExceptionTest6 {
    public void exceptionMethod() throws Exception{
        throw  new Exception(); // 예외 객체를 임의로 발생시켜 주는 예약어
    }
    /**
     * throws 테스트
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ExceptionTest6 et6 = new ExceptionTest6();
        try{
            et6.exceptionMethod();
        }
        catch(Exception e){
            System.out.println("호출한 메소드에서 예외 처리함");
        }
    }
}

사용자 정의 예외

  • 특정 상황에 대한 예외를 직접 만들어 사용 할때
  • Exception 클래스를 상속 받아서 정의

Exception 생성

package chapter11;

public class LoginException extends Exception {

    LoginException(String msg) {
        super(msg);
    }
}

테스트 - Exception 사용

package chapter11;

import java.util.Scanner;

public class ExceptionEx8 {

    static String user_id = "seo";
    static String user_pw = "smg1234";

    public static void main(String[] args) throws Exception {

        try {
            Scanner scan = new Scanner(System.in);
            System.out.print("아이디 : ");
            String input_id = scan.nextLine();

            System.out.print("비밀번호 : ");
            String input_pw = scan.nextLine();

            if (!user_id.equals(input_id)) {
                throw new LoginException("로그인 : 아이디가 올바르지 않습니다.");
            } else if (!user_pw.equals(input_pw)) {
                throw new LoginException("로그인: 비밀번호가 올바르지 않습니다.");
            } else {
                System.out.println("로그인 성공");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }


}

'Programing > JAVA' 카테고리의 다른 글

컬렉션 F/W COLLECTION  (2) 2022.03.07
JAVA- API  (1) 2022.03.07
인터페이스 INTERFACE  (1) 2022.03.04
상속 INHERITANCE_Part3  (0) 2022.03.03
상속 INHERITANCE_Part2  (1) 2022.03.03
'Programing/JAVA' 카테고리의 다른 글
  • 컬렉션 F/W COLLECTION
  • JAVA- API
  • 인터페이스 INTERFACE
  • 상속 INHERITANCE_Part3
쿠크
쿠크
  • 쿠크
    쿠크 개발자
    쿠크
  • 전체
    오늘
    어제
    • 분류 전체보기 (53)
      • Kubernetes (2)
      • Programing (35)
        • JSP (3)
        • JAVA (22)
        • Spring (5)
        • HTML (5)
      • 이외 (12)
        • Git (2)
        • 임시 잡다함 (6)
        • IntelliJ (1)
        • 에러 모음 (2)
      • OS (2)
        • Linux (2)
      • DataBase (2)
        • Mysql (1)
      • 토이 프로젝트 (0)
        • 게시판 만들기 (0)
      • Spring (0)
      • 부동산 or 주식 (0)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • 링크

    • 깃 허브 주소
  • 공지사항

  • 태그

    MySQL
    Database
    spring-framework
    HTML
    ubuntu
    spring-framwork
    클래스
    kubernetes
    error
    IntelliJ
    jsp
    에러원인
    spring
    스프링 특징
    java
    상속
    MVC
    Linux
    에러 발생
    HTTP란
  • hELLO· Designed By정상우.v4.10.3
쿠크
예외처리 EXCEPTION
상단으로

티스토리툴바