MapleStory Finger Point

๐ŸŸค JAVA/๐ŸŸค JAVA ๊ฐœ๋…์ •๋ฆฌ

[JAVA] Exception ์˜ˆ์™ธ ์ฒ˜๋ฆฌ

HYEJU01 2024. 12. 11. 19:03
 

๋ชฉ์ฐจ

 

     

     

     

    ์˜ˆ์™ธ ๋ž€?

    ํ”„๋กœ๊ทธ๋žจ์˜ ์ •์ƒ์ ์ธ ํ๋ฆ„์„ ๋ฐฉํ•ดํ•˜๋Š” ๋ฌธ์ œ ์ƒํ™ฉ (ํ”„๋กœ๊ทธ๋žจ ์ฝ”๋“œ์—์„œ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ , ๋…ผ๋ฆฌ์  ์˜ค๋ฅ˜) 

    ์—๋Ÿฌ๋Š” ๊ทธ๋ณด๋‹ค ๋” ์‹ฌ๊ฐํ•œ ๋ฌธ์ œ (ํ”„๋กœ๊ทธ๋žจ ์ค‘๋‹จ ๋“ฑ์˜ ์‹ฌ๊ฐํ•œ ๋ฌธ์ œ , JVM / ๋ฉ”๋ชจ๋ฆฌ ๋ถ€์กฑ)

     

     

    ์˜ˆ์™ธ ์ข…๋ฅ˜

    • ์ฒดํฌ ์˜ˆ์™ธ : ์ปดํŒŒ์ผ ์‹œ์ ์—์„œ ์˜ˆ์™ธ ๊ฐ•์ œ ์ฒ˜๋ฆฌ
    • ์–ธ์ฒดํฌ ์˜ˆ์™ธ : ๋Ÿฐํƒ€์ž„ ์‹œ์ ์—์„œ ๋ฐœ์ƒ (์ปดํŒŒ์ผ ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ฐ•์ œ ๋˜์ง€ ์•Š์Œ)

     

     

     

     

    ์˜ˆ์™ธ ๊ณ„์ธต ๊ตฌ์กฐ

     

     

    `Throwable` ํด๋ž˜์Šค๋Š” ๋ชจ๋“  ์˜ˆ์™ธ์™€ ์˜ค๋ฅ˜์˜ ๋ถ€๋ชจ ํด๋ž˜์Šค

     

     

    • `getMessage()`: ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
    • `printStackTrace()`: ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ์Šคํƒ ํŠธ๋ ˆ์ด์Šค๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
    • `getCause()`: ์˜ˆ์™ธ์˜ ์›์ธ(๋‹ค๋ฅธ ์˜ˆ์™ธ)์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

     

     

     

    ๊ธฐ๋ณธ ์˜ˆ์™ธ์ฒ˜๋ฆฌ  (try-catch) 

    `try`  ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ์ฝ”๋“œ

    `catch` ์˜ˆ์™ธ ๋ฐœ์ƒ์‹œ ์ฒ˜๋ฆฌ

    `finally` ๊ธฐ๋ณธ ์‹คํ–‰ ๋ธ”๋ก (์ž์›์ •๋ฆฌ ๋“ฑ)

     

     

    ์˜ˆ์™ธ ๋˜์ง€๊ธฐ (throw , throws) 

    `throw` ์˜ˆ์™ธ๋ฅผ ๊ฐ•์ œ๋กœ ๋ฐœ์ƒ

    `throws` ๋ฉ”์„œ๋“œ๊ฐ€ ์˜ˆ์™ธ๋ฅผ ๋˜์งˆ ์ˆ˜ ์žˆ์Œ์„ ์„ ์–ธํ•  ๋•Œ ์‚ฌ์šฉ

     

     

    ์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ

    package try_catch_ex;
    
    import java.util.Scanner;
    
    
    // ์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ ํด๋ž˜์Šค: InvalidAgeException
    class InvalidAgeException extends Exception {
        public InvalidAgeException(String message) {
            super(message); // ๋ถ€๋ชจ ์ƒ์„ฑ์ž ํ˜ธ์ถœ
        }
    }
    
    public class try_catch_ex2 {
    
        public static void main(String[] args){
    
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("๋‚˜์ด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”: ");
            int age = scanner.nextInt();
    
            try {
                validateAge(age);
                System.out.println("์ž…๋ ฅํ•œ ๋‚˜์ด๋Š”: " + age);
            } catch (InvalidAgeException e) {
                System.out.println("์˜ค๋ฅ˜: " + e.getMessage());
            } finally {
                scanner.close();
                System.out.println("ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ.");
            }
    
        }
    
    
        // ๋‚˜์ด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋ฉ”์„œ๋“œ
        public static void validateAge(int age) throws InvalidAgeException {
            if (age < 0 || age > 150) {
                throw new InvalidAgeException("์ž˜๋ชป๋œ ๋‚˜์ด์ž…๋‹ˆ๋‹ค. 0๊ณผ 150 ์‚ฌ์ด์˜ ๊ฐ’์„ ์ž…๋ ฅํ•˜์„ธ์š”.");
            }
        }
    
    }