๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Language/Python

[Python] ์˜ˆ์™ธ์ฒ˜๋ฆฌ try, except, finally and raise | LIM

by forestlim 2022. 6. 24.
728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ python์˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌ

1. try & except

์šฐ๋ฆฌ๊ฐ€ ๋Œ€ํ‘œ์ ์œผ๋กœ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. 

def exception_test(self):
    try:
        abc = 321
        abc.lower()
    except Exception as e:
        print("err message:", e)

 

err message: 'int' object has no attribute 'lower'

 

2. try & except & finally

finally ๊นŒ์ง€ ์ถ”๊ฐ€ํ•˜๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ๊ณผ ๊ด€๊ณ„ ์—†์ด ํ•ญ์ƒ ์‹คํ–‰๋˜๋Š” ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€๋กœ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. 

def exception_test_with_finally(self):
    try:
        abc = 321
        abc.lower()
    except Exception as e:
        print("err message:", e)
    finally:
        print('Process End')

 

err message: 'int' object has no attribute 'lower'
Process End

 

3. try & except & finally & raise

์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋‹ค๊ฐ€ exception์ด ๋ฐœ์ƒํ•ด๋„ finally๋กœ ๊ฐ€์„œ ํ•ญ์ƒ ์‹คํ–‰๋˜์–ด์•ผ ํ•˜๋Š” ์ฝ”๋“œ๋„ ๋™์ž‘๋˜๋ฉด์„œ exception์—์„œ ๋ฐœ์ƒํ•œ error๋„ raise ์‹œํ‚ค๋ฉด ์ข‹๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ํ…Œ์ŠคํŠธ ํ•ด๋ณด์•˜๋‹ค.

 

class raiseError:
    def __init__(self):
        pass
    def test(self):
        try:
            abc = 321
            abc.lower()
        except Exception as e:
            print("err message:", e)
            raise Exception(e)
        finally:
            print('Process End')



def exception_test_with_finally_and_raise():
    try:
        error_test = raiseError()
        error_test.test()
    except Exception as e:
        print(f'์—๋Ÿฌ๋ฉ”์‹œ์ง€ - {e}')

 

err message: 'int' object has no attribute 'lower'
Process End
์—๋Ÿฌ๋ฉ”์‹œ์ง€ - 'int' object has no attribute 'lower'

 

exception์ด ๋ฐœ์ƒํ•ด๋„ ๋จผ์ € finally๋กœ ๊ฐ€์„œ ๋งˆ์ง€๋ง‰๊นŒ์ง€ ์ฒ˜๋ฆฌํ•œ๋‹ค์Œ raise ๋œ ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

์ด๋ ‡๊ฒŒ ํ•ด๋„ ์ž‘๋™ํ•˜์ง€๋งŒ try-finally ๋งŒ ์จ๋„ ์—๋Ÿฌ๋Š” ์œ„๋กœ throw ๋œ๋‹ค. 

 

class raiseError:
    def __init__(self):
        pass

    def test(self):
        try:
            abc = 321
            abc.lower()
        finally:
            print('Process End')


def exception_test_with_finally_and_raise():
    try:
        error_test = raiseError()
        error_test.test()
    except Exception as e:
        print(f'์—๋Ÿฌ๋ฉ”์‹œ์ง€ - {e}')

 

Process End
์—๋Ÿฌ๋ฉ”์‹œ์ง€ - 'int' object has no attribute 'lower'

 

์—๋Ÿฌ๋Š” ๋ฌด์กฐ๊ฑด ์œ„๋กœ throw ์‹œ์ผœ์•ผ ํ•œ๋‹ค! 

 

๊ตฌ์กฐ๊ฐ€ ๋ณต์žกํ•ด์งˆ์ˆ˜๋ก ์ฝ”๋“œ๊ฐ€ ๋งŽ์•„์งˆ์ˆ˜๋ก ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ์›์ธ์„ ์ฐพ๊ธฐ๊ฐ€ ํž˜๋“ค์–ด์ง„๋‹ค. 

์—๋Ÿฌ๊ฐ€ ๋‚ฌ๋Š”๋ฐ ๊ทธ๋Œ€๋กœ return ๋งŒ ๋˜๋ฉด ์–ด๋””์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋Š” ์ง€ ์•Œ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋ฌด์กฐ๊ฑด raise ๋ฅผ ์‹œํ‚ค์ž!

 

๊ทธ๋Ÿด ๋•Œ๋ฅผ ๋Œ€๋น„ํ•ด์„œ ์—๋Ÿฌ๋ฅผ ์ž˜ ํ•ธ๋“ค๋งํ•ด์•ผํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค!

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€