CodeBlanks Logo Icon CodeBlanks

try/except

Learn to catch exceptions with try/except.

Catch errors with try/except

Code inside a try block may raise an error; the except block catches it so the program keeps running:

try:
    x = int("abc")
except:
    print("Geçersiz giriş")

Here int("abc") raises ValueError; the except block catches it and prints a message. Without try the program would stop.

This is the standard approach for operations that may fail, such as user input and file reading.

Catching specific error types

A bare except: catches all errors, but this is dangerous — it hides unexpected bugs. It is better to catch a specific type:

try:
    x = int("abc")
except ValueError:
    print("Sayı değil")

Here only ValueError is caught. If another error (say TypeError) occurs, the program still crashes — which is the desired behaviour.

Multiple except blocks can also be written: one per type.

Practice Catch ValueError and print a message

Inside a try block write x = int("abc"). Inside an except ValueError: block write print("hata").

Starter code

main.py
# open a try block
# attempt the int conversion
# catch with except ValueError

Sample solution

main.py
try:
    x = int("abc")
except ValueError:
    print("hata")

Expected output

hata

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if an error occurs in the try block?

  • The program crashes
  • The except block runs Correct answer
  • The try block reruns
  • Nothing happens

Explanation: When an error occurs Python leaves the try block and jumps to except.

2 Complete the except keyword

Question
try:
    x = int("abc")
____:
    print("hata")
Answer
try:
    x = int("abc")
except:
    print("hata")

Explanation: The except block catches the error inside try.

3 Match try/except concepts

Term Meaning
try Code that may fail
except Catches the error
ValueError Specific error type
int("abc") Raises ValueError

All lessons in Beginner