filmov
tv
Lesson - 45 : Python3 - Python Exception Handling : Creating custom exception class

Показать описание
**************************************************
**************************************************
Python Exception Handling : Creating custom exception class:
Exception handling enables you handle errors gracefully and do something meaningful about it. Like display a message to user if intended file not found. Python handles exception using try.. except .. block.
You can create a custom exception class by Extending BaseException class or subclass ofBaseException .
Python Exception Handling : Creating custom exception class:
As you can see from most of the exception classes in python extends from theBaseException class. You can derive you own exception class from BaseException class or from sublcass of BaseException like RuntimeError .
class NegativeAgeException(RuntimeError):
def __init__(self, age):
super().__init__()
Above code creates a new exception class named NegativeAgeException , which consists of only constructor which call parent class constructor using super().__init__() and sets theage .
Python Exception Handling : Creating custom exception class:
Using custom exception class :
def enterage(age):
if age < 0:
raise NegativeAgeException("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except NegativeAgeException:
print("Only positive integers are allowed")
except:
print("something is wrong")
**************************************************
Python Exception Handling : Creating custom exception class:
Exception handling enables you handle errors gracefully and do something meaningful about it. Like display a message to user if intended file not found. Python handles exception using try.. except .. block.
You can create a custom exception class by Extending BaseException class or subclass ofBaseException .
Python Exception Handling : Creating custom exception class:
As you can see from most of the exception classes in python extends from theBaseException class. You can derive you own exception class from BaseException class or from sublcass of BaseException like RuntimeError .
class NegativeAgeException(RuntimeError):
def __init__(self, age):
super().__init__()
Above code creates a new exception class named NegativeAgeException , which consists of only constructor which call parent class constructor using super().__init__() and sets theage .
Python Exception Handling : Creating custom exception class:
Using custom exception class :
def enterage(age):
if age < 0:
raise NegativeAgeException("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except NegativeAgeException:
print("Only positive integers are allowed")
except:
print("something is wrong")