언젠가는 되어있겠지
데이터 공부 노트
언젠가는 되어있겠지
전체 방문자
오늘
어제
  • 분류 전체보기 (410)
    • Programming (14)
      • Python (6)
      • Algorithm (8)
    • OS (9)
      • Linux (9)
    • DBMS (2)
      • MySQL (2)
    • IoT Apps (6)
      • AppInventor (5)
      • Arduino (1)
    • LeetCode (151)
      • Easy (136)
      • Medium (13)
      • Hard (2)
    • Course (207)
      • [IBM] Data Science (9)
      • [IBM] Data Engineering (5)
      • [Inflearn] Pandas (12)
      • [Inflearn] Public Data Anal.. (8)
      • [Kaggle] Data Science (49)
      • [Youtube] Informations (2)
      • [Coursera] Machine Learning (40)
      • [Progrmiz] Data Structure A.. (15)
      • [DataQuest] Data Engineerin.. (67)
    • Data Engineering (20)
      • [Data Quest] Handling Datas.. (16)
      • [Data Quest] Data Pipeline (4)
    • Certificate (0)
      • 빅데이터 분석기사 (0)
    • SQLD (0)
    • 하고 싶은 이야기 (0)
    • 소설 (0)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

  • Kaggle Course
  • Data Science

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
언젠가는 되어있겠지

데이터 공부 노트

Programming/Python

[Error] Error and Exception

2022. 8. 16. 16:52

1. Kinds of Error

  • KeyError : 주로 딕셔너리 자료형에서 발생하는 에러이다. 없는 Key값에 접근하려고 할 때 발생하게 된다. 이때 dict.get() 메소드를 사용할 수 있다.
  • ValueError : 부적절한 값을 가진 인자를 받았을 때 발생하는 에러이다. 예를들어 int함수 안에는 int("10")과 같이 숫자로 변경할 수 있는 문자열이 와야 하는데, 숫자로 변경할 수 없는 문자열이 오는 것처럼 부적절한 인자가 올 때 발생한다. 또한 리스트 자료형에서 없는 인덱스 값에 접근하려고 할 때 발생한다.
  • Syntax error : 모든 프로그래밍언어는 고유한 문법을 가지고 있다. 이 문법을 위배해서 프로그래밍 하게되면 문법 에러(syntax error) 를 출력한다.
  • Name error : 지정되지 않은 변수명을 불러오거나 변수명에 할당할 경우 이름 에러(name error)를 출력한다.
  • ZeroDivisionError : 숫자를 0으로 나누려는 경우 발생한다.
  • FileNotFoundError : 존재하지 않는 파일이나 디렉토리에 접근하려고 할때 발생한다.
  • TypeError : 서로 다른 타입으로 연산하려고 할 때 발생한다.
  • AttributeError : 잘못된 메서드나 속성을 호출하거나 대입했을 때 발생한다.
  • ConnectionError : 서버를 켜지 않을 때 발생하며, 이 때 manage.py가 있는 프로젝트 디렉토리로 이동하여 python manage.py runserver를 실행한다.
  • Runtime error : 프로그래밍 언어의 문법은 만족하지만 다른 이유로 컴퓨터가 결과를 출력하지 못할 경우 런타임 에러(Runtime error)를 출력한다.

 

2. Exceptions

2.1 try - except

try: 
    ... 
except [발생오류[as 오류 메시지 변수]]:
    ...

If there is any error while executing codes in try block, then code below except will execute. We can use three types of try - except statement.

 

# Case1 : Use only try, except 
"""This will execute codes under except block whatever error it is.""" 

try: 
    ...
except: 
    ... 

# Case2 : except with raised error 
"""This will execute codes under except block when error is in written case."""

try: 
    ...
except [RaisedError]: 
    ...

# Case3 : except with raised error and its contents 
"""This will execute codes under except block and can store contents of error."""

try: 
    ...
except [RaisedError] as e: 
    ...

2.2 try-finally

Codes under finally block always executes whatever error is. Usually, finally statements is used when we close using resource.

f = open('foo.txt', 'w')
try:
    # 무언가를 수행한다.
finally:
    f.close()

2.3 Dealing multiple errors

If we want to process multiple errors, we can use multiple excep statement like using if-elif statement.

try:
    ...
except 발생 오류1:
   ... 
except 발생 오류2:
   ...

If we want to execute some codes when there is no errors after try block, else statement can help.

try:
    ...
except [발생 오류[as 오류 메시지 변수]]:
    ...
else:  # 오류가 없을 경우에만 수행된다.
    ...

 

3. Raising errors on purpose

When we make program, we need to raise error on purpose. raise command can raise error. For example, when we make class which its heritated class must define fly again, then we can make class Bird below :

class Bird:
    def fly(self):
        raise NotImplementedError

So when we define new class heritating class Bird and if new class didn't define fly method, then fly method of Bird class will return NotImplementedError.

 

4. Usecase of exceptions

4.1 try-except

class SerialHandler(object):
    """
    A class to handle all the serial interactions

    Attributes:
        ser : Serial, the serial object opened by this class.
        port : string, the path/name of the serial object to open.
        timeout : int, the time in seconds indicating the timeout for serial operations.
        values : list, the storage store written data from serial object.
        **This class will be changed as 'BLESerialHandler'**
    """
    def __init__(self, port='', timeout=1, baudrate=9600):
        self.ser = None
        self.port = port
        self.timeout = timeout
        self.baudrate = baudrate
        self.values = []

    def change_port(self, port):
        if self.ser:
            self.ser.close()
            self.ser = None
        self.port = port
        self.open_port()

    def open_port(self):
        if not self.port:
            return

        if self.ser:
            self.ser.close()
            self.ser = None

        try:
            self.ser = serial.Serial(self.port, 9600, timeout=self.timeout)
        except serial.SerialException as e:
            self.ser = None
            logger.exception('Error opening serial: %s', e)

4.2 try-finally

def send_db(file):
    reader = csv.reader(file)
    header = next(reader)

    try:
        conn = sqlite3.connect('arduino.db')
        cursor = conn.cursor()

        # Error if there is previous User_name and Date
        for row in reader:
            query = f"INSERT INTO arduino VALUES (?, ?, ?, ?, ?);"
            cursor.execute(query, (row[0], row[1], row[2], row[3], row[4]))
        conn.commit()
    finally:
        conn.close()
        print("Uploading work has been done!")

 

5. Source of the contents 

https://wikidocs.net/30

 

05-4 예외 처리

프로그램을 만들다 보면 수없이 많은 오류를 만나게 된다. 물론 오류가 발생하는 이유는 프로그램이 잘못 동작하는 것을 막기 위한 파이썬의 배려이다. 하지만 때때로 이러한 오류 ...

wikidocs.net

 

'Programming > Python' 카테고리의 다른 글

[DS] Heap  (0) 2022.09.03
[DS] Queue  (0) 2022.09.03
[BeautifulTable] Print list object in table format  (0) 2022.07.04
[Pandas] Return multiple columns  (0) 2022.07.03
[BeautifulSoup] Web Scraping  (0) 2022.07.03
    'Programming/Python' 카테고리의 다른 글
    • [DS] Heap
    • [DS] Queue
    • [BeautifulTable] Print list object in table format
    • [Pandas] Return multiple columns
    언젠가는 되어있겠지
    언젠가는 되어있겠지

    티스토리툴바