출처 : http://thepythonguru.com/python-exception-handling/
# define Python user-defined exceptionsclass Error(Exception):"""Base class for other exceptions"""passclass ValueTooSmallError(Error):"""Raised when the input value is too small"""passclass ValueTooLargeError(Error):"""Raised when the input value is too large"""pass# our main program# user guesses a number until he/she gets it right# you need to guess this numbernumber = 10while True:try:i_num = int(input("Enter a number: "))if i_num < number:raise ValueTooSmallErrorelif i_num > number:raise ValueTooLargeErrorbreakexcept ValueTooSmallError:print("This value is too small, try again!")print()except ValueTooLargeError:print("This value is too large, try again!")print()print("Congratulations! You guessed it correctly.")
How to catch some TYPES of errors before they happen
"""Caveat:The following is not necessarily themost robust way of handling exceptions, IMO.Python allows you to write custom exceptionsthat one can `raise from` others for good reason.This is just meant as a way to think about how wewould model the initial scenario described."""from typing import NamedTuple, Optionalimport requestsimport loggingimport jsonimport enumclass ApiInteraction(enum.Enum):"""The 3 possible states we can expect when interacting with the API."""SUCCESS = 1ERROR = 2FAILURE = 3class ApiResponse(NamedTuple):"""This is sort of a really dumbed-down version of an HTTP response,if you think of it in terms of status codes and response bodies."""status: ApiInteractionpayload: Optional[dict]def hit_endpoint(url: str) -> ApiResponse:"""1. Send an http request to a url2. Parse the json response as a dictionary3. Return an ApiResponse object"""try:response = requests.get(url) # step 1payload = response.json() # step 2except json.decoder.JSONDecodeError as e:# something went wrong in step 2; we knew this might happen# log a simple error messagelogging.error(f'could not decode json from {url}')# log the full traceback at a lower levellogging.info(e, exc_info=True)# since we anticipated this error, make thereturn ApiResponse(ApiInteraction.ERROR, None)# 'except Exception' is seen as an anti-pattern by many but# this is just a trivial example. Another article for another time.except Exception as e:# something went wrong in step 1 or 2 that# we couldn't anticipate# log the exception with the tracebacklogging.error(f"Something bad happened trying to reach {url}")logging.info(e, exc_info=True)# Since something catastrophic happened that# we didn't anticipate i.e. (DivideByBananaError)# we set the ApiResponse.status to FAILUREreturn ApiResponse(ApiInteraction.FAILURE, None)else:# Everything worked as planned! No errors!return ApiResponse(ApiInteraction.SUCCESS, payload)# Python is awesome. We can either use the function by itself# or use it as a constructor for our ApiResponse class# by doing thefollowing:ApiResponse.from_url = hit_endpoint
def test_endpoint_response():url = '<http://httpbin.org/headers'response> = ApiResponse.from_url(url)assert response.status == ApiInteraction.SUCCESSassert response.status == hit_endpoint(url).status # our function and constructor work the same!assert response.payload is not Noneurl = '<http://twitter.com>'response = ApiResponse.from_url(url)assert response.status == ApiInteraction.ERRORassert response.status == hit_endpoint(url).statusassert response.payload is Noneurl = 'foo'response = ApiResponse.from_url(url)assert response.status == ApiInteraction.FAILUREassert response.status == hit_endpoint(url).statusassert response.payload is Nonetest_endpoint_response()