구문 에러 (Syntax Error)
논리 에러 (Logical Error)
예외 (Exception)
4 + spam*3
a = 10
b = 0
c = a / b
def division():
for n in range(0, 5):
print(10.0 / n)
division()
'2' + 2
l = [1, 2]
print(l[2])
d = {"a": 1, "b": 2}
print(d['c'])
a = open('aaa.txt')
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning
try:
(예외 발생 가능한) 일반적인 수행문들
except Exception:
예외가 발생하였을 때 수행되는 문들
else:
예외가 발생하지 않았을 때 수행되는 문들
finally:
예외 발생 유무와 관계없이 무조건 수행되는 문들
try:
print(1.0 / 0.0)
except ZeroDivisionError:
print('zero division error!!!')
def division():
for n in range(0, 5):
try:
print(10.0 / n)
except ZeroDivisionError as e:
print("ZeroDivisionError 발생")
print("-----" + str(e))
print("-----" + e.__str__())
print("-----" + str(e.__class__))
division()
def division():
for n in range(0, 5):
try:
print(10.0 / n)
else:
print("Success")
division()
try:
spam()
except NameError as e:
print('Error -', e)
def zero_division():
x = 1 / 0
try:
zero_division()
except ZeroDivisionError as e:
print('zero division error!!! -', e)
def zero_division():
try:
x = 1 / 0
except ZeroDivisionError as e:
print('Inner - zero division error!!! -', e)
try:
zero_division()
except ZeroDivisionError as e:
print('Outer - zero division error!!! -', e)
try:
spam()
print(1.0 / 0.0)
except:
print('Error')
b = 0.0
name = 'aaa.txt'
try:
print(1.0 / b)
spam()
f = open(name, 'r')
'2' + 2
except NameError:
print('NameError !!!')
except ZeroDivisionError:
print('ZeroDivisionError !!!')
except (TypeError, IOError):
print('TypeError or IOError !!!')
else:
print('No Exception !!!')
finally:
print('Exit !!!')
%ls t.txt
import os
print(os.getcwd())
filename = 't.txt'
try:
f = open(filename, 'r')
except IOError as e:
print(e)
else:
a = float(f.readline())
try:
answer = 1.0 / a
except ZeroDivisionError as e:
print(e)
else:
print(answer)
finally:
print("Finally!!!")
f.close()
%ls a.txt
%cat a.txt
import os
print(os.getcwd())
filename = 't.txt'
default_filename = 'a.txt'
try:
f = open(filename, 'r')
except IOError as e:
print(e)
f = open(default_filename, 'r')
a = float(f.readline())
try:
answer = 1.0 / a
except ZeroDivisionError as e:
print(e)
else:
print(answer)
finally:
print("Finally!!!")
f.close()
def dosomething():
a = 1/0
try:
dosomething()
except ArithmeticError:
print("ArithmeticException occured")
def dosomething():
a = 1/0
try:
dosomething()
except ZeroDivisionError: # ZeroDivisionError는 이곳에서 잡힌다.
print("ZeroDivisionError occured")
except ArithmeticError: # FloatingPointError, OverflowError는 이곳에서 잡힌다.
print("ArithmeticException occured")
def dosomething():
a = 1/0
try:
dosomething()
except ArithmeticError:
print("ArithmeticException occured")
except ZeroDivisionError: # 이곳에서 ZeroDivisionError는 잡히지 않는다. ==> 잘못된 코드
print("ZeroDivisionError occured" )
class SquareSeq:
def __init__(self, n):
self.n = n
def __getitem__(self, k):
if k >= self.n or k < 0 :
raise IndexError # 첨자 범위를 벗어나면 IndexError 예외를 발생시킴
return k * k
def __len__(self):
return self.n
s = SquareSeq(10)
print(s[2], s[4])
for x in s: # IndexError가 발생하는 시점까지 반복한다
print(x,end=" ")
print(s[20]) # 첨자 범위가 넘었다
class Big(Exception):
pass
class Small(Big):
pass
def dosomething1():
x = Big()
raise x
def dosomething2():
raise Small()
for f in (dosomething1, dosomething2):
try:
f()
except Big:
print("Big Exception occurs!")
def f():
raise Exception('message!!!')
try:
f()
except Exception as e:
print(e)
a = 10
b = 0
try:
if b == 0:
raise ArithmeticError('0으로 나누고 있습니다.')
a / b
except ArithmeticError as e:
print(e)