본문 바로가기
Python/기본

[Python] 예외 처리

by 카피마스터 2024. 9. 14.

* 예외 발생 시키기

# raise [예외타입]([메시지])
raise Exception("예외 발생")

 

* try - except

에러가 발생하는 부분에 try로 감싸고 에러발생시 처리를 except에 설정

# 테스트용 예외 발생 클래스
class ExceptTestClass:
    # 함수 호출시 예외 발생
    
    # 1
    def Test1(self):
        raise ZeroDivisionError("0으로 나누기 예외")
    
    # 3
    def Test2(self):
        raise OverflowError("오버 플로우")

# Go Go
print("Start")

try:
    tc = ExceptTestClass()
    tc.Test1()
    print("정상 플레이")
except:
    print("예외 발생")

print("End")

 

결과

 

 

* 예외 타입에 따른 처리

except에 예외 타입을 설정하여 타입에 따른 처리를 할수 있다

# 테스트용 예외 발생 클래스
class ExceptTestClass:
    # 함수 호출시 예외 발생
    
    # 1
    def Test1(self):
        raise ZeroDivisionError("0으로 나누기 예외")
    
    # 3
    def Test2(self):
        raise OverflowError("오버 플로우")

# Go Go
print("Start")

try:
    tc = ExceptTestClass()
    tc.Test1()
    print("정상 플레이")
except ZeroDivisionError as e:  # as e로 에러 내용을 확인 할 수 있다
    print("ZeroDivisionError에 대한 처리({EXCEP})".format(EXCEP=e))
except OverflowError as e:
    print("OverflowError 대한 처리({EXCEP})".format(EXCEP=e))

print("End")

 

결과

 

발생하는 예외가 많고 공통으로 처리해도 되는 경우 상위 에러 객체로 예외처리가 가능하다

ZeroDivisionError와 OverflowError는 Exception의 하위 클래스이기 때문에 Exception으로 예외 처리가 가능하다

try:
    tc = ExceptTestClass()
    tc.Test1()
    print("정상 플레이")
except Exception as e:  # as e로 에러 내용을 확인 할 수 있다
    # Exception으로 예외처리 가능
    print("예외에 대한 처리({EXCEP})".format(EXCEP=e))

 

 

* try - except - else

예외가 발생하지 않는경우 처리가 필요하다면 else에 설정 할 수 있다

# 테스트용 예외 발생 클래스
class ExceptTestClass:
    # 함수 호출시 예외 발생
    
    # 1
    def Test1(self):
        raise ZeroDivisionError("0으로 나누기 예외")
    
    # 3
    def Test2(self):
        raise OverflowError("오버 플로우")

# Go Go
print("Start")

try:
    tc = ExceptTestClass()
    #tc.Test1()
    print("정상 플레이")
except Exception as e:  # as e로 에러 내용을 확인 할 수 있다
    # Exception으로 예외처리 가능
    print("예외에 대한 처리({EXCEP})".format(EXCEP=e))
else:
    print("예외가 발생하지 않음")

print("End")

 

결과

 

 

* try - except - finally

finally에 설정되는 부분은 예외가 발생여부와 상관없이 호출된다

try - except - else - finally형태로도 사용이 가능하다

 

 

selenium 에서 예외처리

selenium 에서 xpath로 경로를 검색시 없는 경로를 입력하면 예외가 발생하게 된다

...

# 크롬 드라이버를 얻고 구글에 접속
driver = Chrome(chrome_options)
driver.get("https://www.google.com")
input_element = driver.find_element(By.XPATH, 'wrong_path')

 

NoSuchElementException 발생

 

 

해당 부분을 try - except 를 이용해서 예외 발생시 처리를 할수 있다

try:
    # 정상적으로 element를 얻은경우 추가적인 처리를 한다
    input_element = driver.find_element(By.XPATH, 'wrong_path')
except:
    # 잘못된 경로인 경우 브라우저를 닫는다
    print("no such element")
    driver.quit()

 

 

except에 예외를 지정하여 특정 예외만 처리할수도 있다

try:
    # 정상적으로 element를 얻은경우 추가적인 처리를 한다
    input_element = driver.find_element(By.XPATH, 'wrong_path')
except selenium.common.exceptions.NoSuchElementException:
    # 잘못된 경로인 경우 브라우저를 닫는다
    print("no such element")
    driver.quit()
except selenium.common.exceptions.JavascriptException:
    # 자바 스크립트를 실행하다가 에러 발생
    print("JavascriptException")

 

 

 

 

'Python > 기본' 카테고리의 다른 글

[Python] 내장 함수  (0) 2024.10.05
[Python] String  (1) 2024.09.15
[Python] 반복문 for  (1) 2024.09.08
[Python] list  (0) 2024.09.08
[Python] 클래스  (0) 2024.09.07