Pemrograman Berorientasi Objek di Python
Alex Yarosh
Content Quality Analyst @ DataCamp
a = 1
a / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
1/0
ZeroDivisionError: pembagian dengan nol
a = [1,2,3]
a[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
a[5]
IndexError: indeks daftar di luar jangkauan
a = 1
a + "Hello"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
a + "Hello"
TypeError: tipe operan tidak didukung untuk +: /
'int' dan 'str'
a = 1
a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
a + b
NameError: nama 'b' tidak terdefinisi
try - except - finally:try: # Coba jalankan beberapa kodeexcept ExceptionNameHere: # Jalankan kode ini jika ExceptionNameHere terjadiexcept AnotherExceptionHere: #<-- beberapa blok except # Jalankan kode ini jika AnotherExceptionHere terjadi ...finally: #<-- opsional # Jalankan kode ini apapun yang terjadi
raise ExceptionNameHere('Pesan kesalahan di sini')def make_list_of_ones(length):
if length <= 0:
raise ValueError("Panjang tidak valid!") # <--- Akan menghentikan program dan menimbulkan kesalahan
return [1]*length
make_list_of_ones(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
make_list_of_ones(-1)
File "<stdin>", line 3, in make_list_of_ones
raise ValueError("Panjang tidak valid!")
ValueError: Panjang tidak valid!
BaseException atau ExceptionBaseException
+-- Exception
+-- ArithmeticError # <---
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError # <---
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- RuntimeError
...
+-- SystemExit
...
Exception atau salah satu subclass-nyaclass BalanceError(Exception): pass
class Customer:
def __init__(self, name, balance):
if balance < 0 :
raise BalanceError("Saldo harus tidak negatif!")
else:
self.name, self.balance = name, balance
cust = Customer("Larry Torres", -100)
Traceback (most recent call last):
File "script.py", line 11, in <module>
cust = Customer("Larry Torres", -100)
File "script.py", line 6, in __init__
raise BalanceError("Saldo harus tidak negatif!")
BalanceError: Saldo harus tidak negatif!
cust
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cust
NameError: name 'cust' is not defined
try:
cust = Customer("Larry Torres", -100)
except BalanceError:
cust = Customer("Larry Torres", 0)
Pemrograman Berorientasi Objek di Python