অন্য হাই-লেভেল ল্যাঙ্গুয়েজের মতো পাইথনে এক্সসেপশন রয়েছে। সমস্যা হলে এক্সসেপশন উত্থাপিত হয়। বিভিন্ন ধরনের এক্সসেপশন আছে যেমন ZeroDivisionError, AssertionError ইত্যাদি। সকল এক্সসেপশন ক্লাস BaseException ক্লাস থেকে ডেরাইভড।
কোড বিল্ট-ইন এক্সসেপশন রান করতে পারে, অথবা আমরা কোডে নিজেও এই এক্সসেপশনগুলো উত্থাপন করতে পারি। ইউজার Exception ক্লাস থেকে, অথবা Exception-এর যেকোনো চাইল্ড ক্লাস থেকে নিজস্ব এক্সসেপশন ডেরাইভ করতে পারেন।
BaseException সকল এক্সসেপশনের বেস ক্লাস। ইউজার-ডিফাইনড ক্লাস সরাসরি এই ক্লাস থেকে ডেরাইভ করা যায় না; ইউজার-ডিফাইনড ক্লাসের জন্য Exception ক্লাস ব্যবহার করতে হয়।
পাইথন এক্সসেপশন হায়ারার্কি (Hierarchy) নিচের মতো:
- BaseException
- Exception
- ArithmeticError
- FloatingPointError
- OverflowError
- ZeroDivisionError
- AssertionError
- AttributeError
- BufferError
- EOFError
- ImportError
- ModuleNotFoundError
- LookupError
- IndexError
- KeyError
- MemoryError
- NameError
- UnboundLocalError
- OSError
- BlockingIOError
- ChildProcessError
- ConnectionError
- BrokenPipeError
- ConnectionAbortedError
- ConnectionRefusedError
- ConnectionResetError
- FileExistsError
- FileNotFoundError
- InterruptedError
- IsADirectoryError
- NotADirectoryError
- PermissionError
- ProcessLookupError
- TimeoutError
- ArithmeticError
- ReferenceError
- RuntimeError
- NotImplementedError
- RecursionError
- StopIteration
- StopAsyncIteration
- SyntaxError
- IndentationError
- TabError
- IndentationError
- SystemError
- TypeError
- ValueError
- UnicodeError
- UnicodeDecodeError
- UnicodeEncodeError
- UnicodeTranslateError
- UnicodeError
- Warning
- BytesWarning
- DeprecationWarning
- FutureWarning
- ImportWarning
- PendingDeprecationWarning
- ResourceWarning
- RuntimeWarning
- SyntaxWarning
- UnicodeWarning
- UserWarning
- GeneratorExit
- KeyboardInterrupt
- SystemExit
সমস্যা − এখানে একটি Employee ক্লাস আছে। শর্ত হলো কর্মীর বয়স অবশ্যই ১৮ বছরের বেশি হতে হবে।
আমাদের একটি ইউজার-ডিফাইনড এক্সসেপশন ক্লাস তৈরি করতে হবে, যা Exception ক্লাসের চাইল্ড ক্লাস হবে।
উদাহরণ কোড
class LowAgeError(Exception): def __init__(self): pass def __str__(self): return 'The age must be greater than 18 years' class Employee: def __init__(self, name, age): self.name = name if age < 18: raise LowAgeError else: self.age = age def display(self): print('The name of the employee: ' + self.name + ', Age: ' + str(self.age) +' Years') try: e1 = Employee('Subhas', 25) e1.display() e2 = Employee('Anupam', 12) e1.display() except LowAgeError as e: print('Error Occurred: ' + str(e))আউটপুট
The name of the employee: Subhas, Age: 25 Years Error OccurredThe age must be greater than 18 years