MulaiMulai sekarang secara gratis

Custom exceptions

You don't have to rely solely on built-in exceptions like IndexError: you can define custom exceptions that are more specific to your application. You can also define exception hierarchies. All you need to define an exception is a class inherited from the built-in Exception class or one of its subclasses.

Earlier in the course, you defined an Employee class and used print statements and default values to handle errors like creating an employee with a salary below the minimum or giving a raise that is too large. A better way to handle this situation is to use exceptions - because these errors are specific to our application (unlike, for example, a division by zero error, which is universal), it makes sense to use custom exception classes.

Latihan ini adalah bagian dari kursus

Introduction to Object-Oriented Programming in Python

Lihat Kursus

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# Define SalaryError inherited from ValueError
____


# Define BonusError inherited from SalaryError
____
Edit dan Jalankan Kode