Asosiy matnga o'tish
ITIT Interview
Python

Xatolar va fayllar

try, except, else, finally, xatolar ierarxiyasi, raise va raise from, maxsus xatolar, EAFP va LBYL, fayllar bilan ishlash, pathlib va JSON.

O'rganildi: 0 / 5
Progress

Xatolarni ushlash

try:
    value = int(user_input)
    result = 100 / value
except ValueError:
    print("Son kiriting")
except ZeroDivisionError as e:
    print(f"Nolga bo'lish: {e}")
else:
    print("Xato bo'lmadi:", result)      # faqat try muvaffaqiyatli bo'lsa
finally:
    print("Har doim bajariladi")          # resurslarni tozalash
BlokQachon bajariladi
tryHar doim
exceptMos xato yuz berganda
elseXato bo'lmaganda
finallyHar doim, hatto return yoki ushlanmagan xatoda ham

Xatolar ierarxiyasi

BaseException
 ├── SystemExit, KeyboardInterrupt, GeneratorExit
 └── Exception
      ├── ValueError, TypeError, KeyError, IndexError, AttributeError
      ├── ArithmeticError → ZeroDivisionError
      ├── OSError → FileNotFoundError, PermissionError, ConnectionError
      └── ...

except: yoki except BaseException: dan qoching: ular Ctrl+C (KeyboardInterrupt) va sys.exit() ni ham ushlaydi. Eng kamida except Exception: yozing, yaxshisi — aniq xato turini.

Xato tashlash

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError(f"Mablag' yetarli emas: {balance} < {amount}")
    return balance - amount

try:
    config = json.loads(text)
except json.JSONDecodeError as e:
    raise ConfigError("Konfiguratsiya buzilgan") from e   # asl sababni saqlaydi

try:
    ...
except Exception:
    logger.exception("Kutilmagan xato")
    raise          # xuddi shu xatoni qayta tashlash, traceback saqlanadi

Maxsus xatolar

class AppError(Exception):
    """Ilovaning barcha xatolari uchun asos."""

class NotFoundError(AppError):
    def __init__(self, resource: str, id: int):
        super().__init__(f"{resource} #{id} topilmadi")
        self.resource = resource
        self.id = id

EAFP va LBYL

# LBYL — Look Before You Leap (avval tekshir)
if "email" in user:
    send(user["email"])

# EAFP — Easier to Ask Forgiveness than Permission (Python uslubi)
try:
    send(user["email"])
except KeyError:
    pass

EAFP Python'da odatiy: tekshiruv va amal orasidagi poyga holatini bartaraf etadi (masalan, fayl tekshirilgandan keyin o'chirilishi mumkin).

Fayllar

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Salom\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:                     # qatorma-qator, xotirani tejaydi
        print(line.rstrip())
RejimMa'nosi
"r"O'qish (standart)
"w"Yozish, faylni tozalaydi
"a"Oxiriga qo'shish
"x"Yangi fayl yaratish, bor bo'lsa xato
"b"Binar ("rb", "wb")

encoding="utf-8" ni doim yozing: aks holda Windows'da boshqa kodlash ishlatilishi mumkin.

pathlib

from pathlib import Path

base = Path(__file__).parent
config = base / "config" / "settings.json"     # / bilan yo'l qurish

config.exists()
config.read_text(encoding="utf-8")
config.suffix          # '.json'
for p in base.glob("**/*.py"):
    print(p.name)
Path("logs").mkdir(parents=True, exist_ok=True)

JSON

import json

data = json.loads('{"name": "Ali", "age": 25}')     # str → dict
text = json.dumps(data, ensure_ascii=False, indent=2)   # dict → str (o'zbekcha harflar saqlanadi)

with open("users.json", encoding="utf-8") as f:
    users = json.load(f)

Intervyu savollari

Ushbu sahifada