๐ 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 ๋ฅผ ์ํค์!
๊ทธ๋ด ๋๋ฅผ ๋๋นํด์ ์๋ฌ๋ฅผ ์ ํธ๋ค๋งํด์ผํ๋ ๊ฒ ๊ฐ๋ค!
'Language > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] functools ์ partial | LIM (0) | 2022.07.09 |
---|---|
[Python] Flask์ FastAPI๋ก Python ๋์์ฑ ํ ์คํธ | LIM (0) | 2022.07.03 |
[Python] ์ถ์ ๋ฉ์๋ ABC์ ์ ์์ ์ฌ์ฉ | LIM (0) | 2022.06.19 |
[Python] Thread & Lock ( ์ฐ๋ ๋์ ๋ฝ ) | LIM (0) | 2022.06.15 |
[Python] *args ์ **kwargs | LIM (0) | 2021.01.27 |
๋๊ธ