python/기본

Exception

wefree 2022. 4. 29. 22:45

python exception hierachy

https://docs.python.org/3/library/exceptions.html#exception-hierarchy

l = [1, 2, 3]
i = 5

try:
    l[i]
except IndexError as e:
    print(f"Don't worry: {e}")
except NameError as e:
    print(e)
except Exception as e:
    print(f'other: {e}')
else:
    print('done')  # 예외가 발생하지 않고 잘 수행되었을 때 실행되고, finally 전에 무언가를 수행하고 싶을 때 사용 한다.
finally:
    print("run always")


try:
  result =4/0
except:
  print("error raised")
else:
  print(result)

try:
  4/0
except (ZeroDivisionError, IndexError) as e:
  print(e)
  

####################################################################
class MyException(Exception):
    pass


def check():
    words = ['APPLE', 'orange', 'banana']
    for word in words:
        if word.isupper():
            raise MyException(word)


try:
    check()
except MyException as e:
    print('My fault')