Python menyediakan dua fitur yang sangat penting untuk menangani kesalahan tak terduga dalam program Python Anda dan menambahkan kemampuan debugging di dalamnya.
Table of Contents
- Standard Exceptions
- Creating Custom Exceptions
- Example: User-Defined Exception in Python
- Customizing Exception Classes
- Apa itu Custom Exception Handling python?
- Apa yang dimaksud dengan exception pada python?
- Apa yang anda ketahui tentang exception handling?
- Di dalam statement try apa arti dari except?
- Exception Handling
- Assertions Exception adalah sebuah peristiwa, yang terjadi selama
pelaksanaan program yang mengganggu aliran normal instruksi program. Secara umum, ketika skrip Python menemukan situasi yang tidak dapat diatasi, hal itu menimbulkan pengecualian. Exception adalah objek Python yang mewakili kesalahan.
Ketika skrip Python menimbulkan Exception, ia harus menangani Exception begitu saja sehingga berhenti dan berhenti.
Standard Exceptions
Nama | Penjelasan |
---|
Exception
| Kelas dasar untuk semua pengecualian / exception
|
StopIteration
| Dibesarkan ketika metode (iterator) berikutnya dari iterator tidak mengarah ke objek apa pun.
|
SystemExit
| Dibesarkan oleh fungsi sys.exit ().
|
StandardError
| Kelas dasar untuk semua pengecualian built-in kecuali StopIteration dan SystemExit.
|
ArithmeticError
| Kelas dasar untuk semua kesalahan yang terjadi untuk perhitungan numerik.
|
OverflowError
| Dibesarkan saat perhitungan melebihi batas maksimum untuk tipe numerik.
|
FloatingPointError
| Dibesarkan saat perhitungan floating point gagal.
|
ZeroDivisonError
| Dibesarkan saat pembagian atau modulo nol dilakukan untuk semua tipe numerik.
|
AssertionError
| Dibesarkan jika terjadi kegagalan pernyataan Assert.
|
AttributeError
| Dibesarkan jika terjadi kegagalan referensi atribut atau penugasan.
|
EOFError
| Dibesarkan bila tidak ada input dari fungsi raw_input () atau input () dan akhir file tercapai.
|
ImportError
| Dibesarkan saat sebuah pernyataan impor gagal.
|
KeyboardInterrupt
| Dibesarkan saat pengguna menyela eksekusi program, biasanya dengan menekan Ctrl + c.
|
LookupError
| Kelas dasar untuk semua kesalahan pencarian.
|
IndexError
| Dibesarkan saat sebuah indeks tidak ditemukan secara berurutan.
|
KeyError
| Dibesarkan saat kunci yang ditentukan tidak ditemukan dalam kamus.
|
NameError
| Dibesarkan saat pengenal tidak ditemukan di namespace lokal atau global.
|
UnboundLocalError
| Dibesarkan saat mencoba mengakses variabel lokal dalam suatu fungsi atau metode namun tidak ada nilai yang ditugaskan padanya.
|
EnvironmentError
| Kelas dasar untuk semua pengecualian yang terjadi di luar lingkungan Python.
|
IOError
| Dibesarkan saat operasi input / output gagal, seperti pernyataan cetak atau fungsi open () saat mencoba membuka file yang tidak ada.
|
OSError
| Dibangkitkan untuk kesalahan terkait sistem operasi.
|
SyntaxError
| Dibesarkan saat ada kesalahan dengan sintaks Python.
|
IndentationError
| Dibesarkan saat indentasi tidak ditentukan dengan benar.
|
SystemError
| Dibesarkan saat penafsir menemukan masalah internal, namun bila kesalahan ini ditemui juru bahasa Python tidak keluar.
|
SystemExit
| Dibesarkan saat juru bahasa Python berhenti dengan menggunakan fungsi sys.exit (). Jika tidak ditangani dalam kode, menyebabkan penafsir untuk keluar.
|
TypeError
| Dibesarkan saat operasi atau fungsi dicoba yang tidak valid untuk tipe data yang ditentukan.
|
ValueError
| Dibesarkan ketika fungsi bawaan untuk tipe data memiliki jenis argumen yang valid, namun argumen tersebut memiliki nilai yang tidak valid yang ditentukan.
|
RuntimeError
| Dibesarkan saat kesalahan yang dihasilkan tidak termasuk dalam kategori apa pun.
|
NotImplementedError
| Dibesarkan ketika metode abstrak yang perlu diimplementasikan di kelas warisan sebenarnya tidak dilaksanakan.
|
Edit tutorial ini
Python has numerous built-in exceptions that force your program to output an error when something in the program goes wrong.
However, sometimes you may need to create your own custom exceptions that serve your purpose.
Creating Custom Exceptions
In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either
directly or indirectly, from the built-in Exception
class. Most of the built-in exceptions are also derived from this class.
>>> 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
Here, we have created a user-defined exception called CustomError
which inherits from the Exception
class. This new exception, like other exceptions, can be raised using the raise
statement with an optional error message.
When we are developing a large Python program, it is a good practice to place all the user-defined exceptions that our program raises in
a separate file. Many standard modules do this. They define their exceptions separately as exceptions.py
or errors.py
(generally but not always).
User-defined exception class can implement everything a normal class can do, but we generally make them simple and concise. Most implementations declare a custom base class and derive others exception classes from this base class. This concept is made clearer in the following example.
Example:
User-Defined Exception in Python
In this example, we will illustrate how user-defined exceptions can be used in a program to raise and catch errors.
This program will ask the user to enter a number until they guess a stored number correctly. To help them figure it out, a hint is provided whether their guess is greater than or less than the stored number.
# 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.")
Here is a sample run of this program.
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.
We have defined a base class called Error
.
The other two
exceptions (ValueTooSmallError
and ValueTooLargeError
) that are actually raised by our program are derived from this class. This is the standard way to define user-defined exceptions in Python programming, but you are not limited to this way only.
Customizing Exception Classes
We can further customize this class to accept other arguments as per our needs.
To learn about customizing the Exception classes, you need to have the basic knowledge of
Object-Oriented programming.
Visit Python Object Oriented Programming to start learning about Object-Oriented programming in Python.
Let's look at one example:
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)
Output
Enter salary amount: 2000
Traceback (most recent call last):
File "", line 17, in
raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range
Here, we have overridden the constructor of the Exception
class to accept our own custom arguments salary
and message
. Then, the constructor of the parent Exception
class is called manually with the self.message
argument using super()
.
The custom self.salary
attribute is
defined to be used later.
The inherited __str__
method of the Exception
class is then used to display the corresponding message when SalaryNotInRangeError
is raised.
We can also customize the __str__
method itself by overriding it.
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)
Output
Enter salary amount: 2000
Traceback (most recent call last):
File "/home/bsoyuj/Desktop/Untitled-1.py", line 20, in
raise SalaryNotInRangeError(salary)
__main__.SalaryNotInRangeError: 2000 -> Salary is not in (5000, 15000) range
To learn more about how you can handle exceptions in Python, visit Python Exception Handling.
Apa itu Custom Exception Handling python?
Python
Exception handling adalah suatu mekanisme penanganan flow normal program karena terjadi exception dengan melanjutkan flow ke code block lainnya. Kenapa harus menangani exception? Karena terjadi exception dan kita tidak tangani, maka program akan berhenti.
Apa yang dimaksud dengan exception pada python?
Python menyediakan dua fitur yang sangat penting untuk menangani
kesalahan tak terduga dalam program Python Anda dan menambahkan kemampuan debugging di dalamnya. Assertions Exception adalah sebuah peristiwa, yang terjadi selama pelaksanaan program yang mengganggu aliran normal instruksi program.
Apa yang anda ketahui tentang exception handling?
Exception Handling merupakan mekanisme yang paling diperlukan dalam menangani error yang terjadi
pada saat runtime (program berjalan) atau yang lebih dikenal dengan sebutan runtime error. Secara umum, adanya kesalahan / error yang terjadi pada program pada saat runtime dapat menyebabkan program berhenti atau hang.
Di dalam statement try apa arti dari except?
except untuk menangani error yang mungkin kita sendiri tidak mengetahuinya. Biasanya try.. except ini
digunakan untuk menangani error saat penggunaan IO, operasi database, atau pengaksesan indeks suatu list atau dictionary, dan berbagai kasus lainnya.
Apa itu Exception pada python?
Assertions Exception adalah sebuah peristiwa, yang terjadi selama pelaksanaan program yang mengganggu aliran normal instruksi program. Secara umum, ketika skrip Python menemukan situasi yang tidak dapat diatasi, hal itu menimbulkan pengecualian. Exception adalah objek Python yang mewakili kesalahan.
Apa itu Custom Exception Handling python?
Python Exception handling adalah suatu mekanisme penanganan flow normal program karena terjadi exception dengan melanjutkan flow ke code block lainnya. Kenapa harus menangani exception? Karena terjadi exception dan kita tidak tangani, maka program akan berhenti.
Apa itu ZeroDivisionError?
ZeroDivisionError: Exception ini muncul ketika kamu menyediakan angka 0 argumen kedua untuk operasi pembagian atau modulo. FileNotFoundError: Exception ini muncul ketika berkas atau direktori yang program minta tidak ditemukan atau tidak ada.
Di dalam statement try apa arti dari except?
except untuk menangani error yang mungkin kita sendiri tidak mengetahuinya. Biasanya try.. except ini digunakan untuk menangani error saat penggunaan IO, operasi database, atau pengaksesan indeks suatu list atau dictionary, dan berbagai kasus lainnya.