산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python 사용자 정의 예외

Python 사용자 정의 예외

이 자습서에서는 예제를 통해 요구 사항에 따라 사용자 지정 예외를 정의하는 방법을 배웁니다.

Python에는 프로그램에 문제가 있을 때 프로그램에서 강제로 오류를 출력하도록 하는 수많은 내장 예외가 있습니다.

그러나 때로는 목적에 맞는 사용자 정의 예외를 생성해야 할 수도 있습니다.

<시간>

사용자 정의 예외 생성

Python에서 사용자는 새 클래스를 생성하여 사용자 정의 예외를 정의할 수 있습니다. 이 예외 클래스는 내장 Exception에서 직접 또는 간접적으로 파생되어야 합니다. 수업. 대부분의 기본 제공 예외도 이 클래스에서 파생됩니다.

>>> class CustomError(Exception):
...     pass
...

>>> raise CustomError
Traceback (most recent call last):
...
__main__.CustomError

>>> raise CustomError("An error occurred")
Traceback (most recent call last):
...
__main__.CustomError: An error occurred

여기에서 CustomError라는 사용자 정의 예외를 만들었습니다. Exception에서 상속 수업. 이 새로운 예외는 다른 예외와 마찬가지로 raise를 사용하여 발생할 수 있습니다. 선택적 오류 메시지가 있는 문.

대규모 Python 프로그램을 개발할 때 프로그램에서 발생시키는 모든 사용자 정의 예외를 별도의 파일에 배치하는 것이 좋습니다. 많은 표준 모듈이 이 작업을 수행합니다. 예외를 exceptions.py로 별도로 정의합니다. 또는 errors.py (일반적으로 하지만 항상 그런 것은 아님).

사용자 정의 예외 클래스는 일반 클래스가 할 수 있는 모든 것을 구현할 수 있지만 일반적으로 간단하고 간결하게 만듭니다. 대부분의 구현은 사용자 지정 기본 클래스를 선언하고 이 기본 클래스에서 다른 예외 클래스를 파생시킵니다. 이 개념은 다음 예에서 더 명확해집니다.

<시간>

예:Python의 사용자 정의 예외

이 예에서는 사용자 정의 예외를 프로그램에서 사용하여 오류를 발생시키고 잡는 방법을 설명합니다.

이 프로그램은 저장된 숫자를 정확하게 추측할 때까지 사용자에게 숫자를 입력하도록 요청합니다. 그들이 그것을 알아낼 수 있도록 그들의 추측이 저장된 숫자보다 크거나 작은지 여부에 대한 힌트가 제공됩니다.

# define Python user-defined exceptions
class Error(Exception):
    """Base class for other exceptions"""
    pass


class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass


class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass


# you need to guess this number
number = 10

# user guesses a number until he/she gets it right
while True:
    try:
        i_num = int(input("Enter a number: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except 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.")

다음은 이 프로그램의 샘플 실행입니다.

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

Error이라는 기본 클래스를 정의했습니다. .

다른 두 예외(ValueTooSmallErrorValueTooLargeError ) 우리 프로그램에서 실제로 제기한 것은 이 클래스에서 파생되었습니다. 이것은 Python 프로그래밍에서 사용자 정의 예외를 정의하는 표준 방법이지만 이 방법에만 국한되지 않습니다.

<시간>

예외 클래스 사용자 정의

필요에 따라 다른 인수를 허용하도록 이 클래스를 추가로 사용자 지정할 수 있습니다.

Exception 클래스를 사용자 정의하는 방법을 배우려면 객체 지향 프로그래밍에 대한 기본 지식이 필요합니다.

Python 객체 지향 프로그래밍을 방문하여 Python의 객체 지향 프로그래밍 학습을 시작하십시오.

한 가지 예를 살펴보겠습니다.

class SalaryNotInRangeError(Exception):
    """Exception raised for errors in the input salary.

    Attributes:
        salary -- input salary which caused the error
        message -- explanation of the error
    """

    def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
        self.salary = salary
        self.message = message
        super().__init__(self.message)


salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
    raise SalaryNotInRangeError(salary)

출력

Enter salary amount: 2000
Traceback (most recent call last):
  File "<string>", line 17, in <module>
    raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range

여기에서 Exception의 생성자를 재정의했습니다. 자체 사용자 정의 인수를 허용하는 클래스 salarymessage . 그런 다음 부모 Exception의 생성자는 클래스는 self.message를 사용하여 수동으로 호출됩니다. super()을 사용한 인수 .

맞춤 self.salary 속성은 나중에 사용하도록 정의됩니다.

상속된 __str__ Exception 메소드 그런 다음 클래스는 SalaryNotInRangeError일 때 해당 메시지를 표시하는 데 사용됩니다. 제기됩니다.

__str__를 사용자 정의할 수도 있습니다. 재정의하여 메서드 자체를 재정의합니다.

class SalaryNotInRangeError(Exception):
    """Exception raised for errors in the input salary.

    Attributes:
        salary -- input salary which caused the error
        message -- explanation of the error
    """

    def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
        self.salary = salary
        self.message = message
        super().__init__(self.message)

    def __str__(self):
        return f'{self.salary} -> {self.message}'


salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
    raise SalaryNotInRangeError(salary)

출력

Enter salary amount: 2000
Traceback (most recent call last):
  File "/home/bsoyuj/Desktop/Untitled-1.py", line 20, in <module>
    raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: 2000 -> Salary is not in (5000, 15000) range
<시간>

Python에서 예외를 처리하는 방법에 대해 자세히 알아보려면 Python 예외 처리를 방문하세요.


python

  1. 파이썬 데이터 유형
  2. 파이썬 연산자
  3. 파이썬 통과 문
  4. 파이썬 함수 인수
  5. 파이썬 사전
  6. Python 오류 및 내장 예외
  7. 파이썬 객체 지향 프로그래밍
  8. 파이썬 상속
  9. 파이썬 반복자
  10. 예제가 있는 Python의 type() 및 isinstance()