3. Exception Handling

2024. 3. 14. 01:09·Python
3python-exceptions

Exception Handling¶

Exceptions are mechanism for handling runtime errors. A simple example:

In [2]:
dict = {"a":1, "b":2, "c":3}
print(dict["d"])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-0175b692bf59> in <module>
      1 dict = {"a":1, "b":2, "c":3}
----> 2 print(dict["d"])

KeyError: 'd'

KeyError is the exception that was raised. We can check for this and take the appropriate action instead

In [3]:
try: 
    val = dict["d"]
except KeyError:
    val = "error that key is not found"

print(val)
error that key is not found

We have yet to talk about I/O, but when you open a file, you would get an error if the file does not exist.

In [4]:
try: 
    f = open("file.txt", "r")
except IOError:
    print("error: that file does not exist")
error: that file does not exist

We can also get the detail of the exception, and re-raise the exception.

In [5]:
try: 
    1/0
except ZeroDivisionError as detail:
    print("Handling run-time error: ", detail)
    raise
Handling run-time error:  division by zero
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-6628859c5c39> in <module>
      1 try:
----> 2     1/0
      3 except ZeroDivisionError as detail:
      4     print("Handling run-time error: ", detail)
      5     raise

ZeroDivisionError: division by zero

There are many different types of exceptions. You probably won't be able to anticipate every failure mode in advance. In that case, when you run and your code crashes because of an exception, the python interpreter will print out the name of the exception and you can then modify your code to take the appropriate action.

You can catch multiple ones per except clause or have multiple except clauses. You can also use an else clause after successful execution, and a finally clause, which is always executed before exiting the try block.

In [4]:
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.")
    raise
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
else:
    print('Success')
finally:
    print('Goodbye!')
Could not convert data to an integer.
Goodbye!
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-ac2a77cf844b> in <module>
      4     f = open('myfile.txt')
      5     s = f.readline()
----> 6     i = int(s.strip())
      7 except OSError as err:
      8     print("OS error: {0}".format(err))

ValueError: invalid literal for int() with base 10: '100ee'

You can have your own functions raise exceptions when things go wrong and you can build your own exception classes (more later).

'Python' 카테고리의 다른 글

6. Recursion vs. Iteration  (1) 2024.03.14
5. Function  (0) 2024.03.14
4. Conditionals and Loops  (0) 2024.03.14
2. List, Set, Tuple  (1) 2024.03.14
1. Data Types  (0) 2024.03.14
'Python' 카테고리의 다른 글
  • 5. Function
  • 4. Conditionals and Loops
  • 2. List, Set, Tuple
  • 1. Data Types
Juson
Juson
  • Juson
    Juson의 데이터 공부
    Juson
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • RAG (2)
      • AI (2)
        • NLP (0)
        • Generative Model (0)
        • Deep Reinforcement Learning (2)
        • LLM (0)
      • Logistic Optimization (0)
      • Machine Learning (37)
        • Linear Regression (2)
        • Logistic Regression (2)
        • Decision Tree (5)
        • Naive Bayes (1)
        • KNN (2)
        • SVM (2)
        • Clustering (4)
        • Dimension Reduction (3)
        • Boosting (6)
        • Abnomaly Detection (2)
        • Recommendation (4)
        • Embedding & NLP (4)
      • Reinforcement Learning (5)
      • Deep Learning (10)
        • Deep learning Bacis Mathema.. (10)
      • Optimization (2)
        • OR Optimization (0)
        • Convex Optimization (0)
        • Integer Optimization (0)
      • SNA 분석 (0)
      • 포트폴리오 최적화 공부 (0)
        • 최적화 기법 (0)
        • 금융 베이스 (0)
      • Finanancial engineering (0)
      • 프로그래머스 데브코스(Boot camp) (15)
        • SQL (9)
        • Python (5)
        • Machine Learning (1)
      • Python (22)
      • Project (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Juson
3. Exception Handling
상단으로

티스토리툴바