try except

BackEnd_Ash.log·2020년 4월 18일
0

try except 는 어딜가든 많이 사용하게 된다.
만약에 500 에러가 나는것을
400 에러 처리를 할수가 있고
unit test 에서도 어디에서 잘못되었는지
예외문 처리로 확인을 할수가 있고 그것들을 모두 잡아줘야한다.

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

except ValuesError

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

만약에 ,

위으 코드를 보면 int 형이 들어와야 하는데
다른 자료형이 들어왔을때 에러를 발생시킨다.

except KeyError

choice = input("enter v for validate, or enter g for generate").lower()
valid_choices = {'v':1, 'g':1}

try:
    valid_choices[choice]
    #do something

except KeyError:    
    print("Not a valid choice! Try again")
    restartCode()   #pre-defined function, d/w about this

값을 받게하고 거기에 값이 해당되지 않다면 에러를 발생시키는데
이같은 경우는 조건문을 걸어줄수도 있습니다 ^^

except TypeErorr :

def division_function(a,b):
try:
     # a에 b를 나눈다.
     print(a/b);
except TypeError as e:
     print(e);
     # 이 에러는 0으로 나누려고 할 때, 발생하는 에러입니다.
except ZeroDivisionError as e:
     print(e);
     
 # TypeError가 발생할 것을 예상
division_function("a", 1);

이 에러는 타입이 맞지 않는 변수 값으로 계산을 하려할 때 발생, 즉 str타입 / int 타입이면 에러가 발생한다

keyboard error


try :
    model.train(...)
except KeyboardInterrup:
    return 

다음과 같은 상황은 터미널에서 모형을 돌리는 중에 Ctrl + c 를 눌렀거나 ,
주피터 노트북에서 모형을 돌리고 있는중에 stop 을 할때 ,
session 에서 돌아가고 있는 모형이 날라가는 것을 방지해준다.

profile
꾸준함이란 ... ?

0개의 댓글