Language

Exception Handling · Lesson 21 of 56

Exception

Source: 7-Exception Handling/7.1-exception.ipynb

Start here — no coding background needed

What you will learn

Handle mistakes gracefully with try / except.

In simple words

Sometimes code fails (divide by zero, bad input). `try` attempts work; `except` runs a safe backup.

Think of it like this

Try to pay by card; if it fails, pay cash instead.

When something goes wrong, handle it calmly instead of crashing.

Easy example — try this first

Easy example — run this first. Change values and press Run again.

Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference notes (from full bootcamp)

Optional — deeper detail for when you are ready

Understanding Exceptions

Exception handling in Python allows you to handle errors gracefully and take corrective actions without stopping the execution of the program. This lesson will cover the basics of exceptions, including how to use try, except, else, and finally blocks.

What Are Exceptions?

Exceptions are events that disrupt the normal flow of a program. They occur when an error is encountered during program execution. Common exceptions include:

  • ZeroDivisionError: Dividing by zero.
  • FileNotFoundError: File not found.
  • ValueError: Invalid value.
  • TypeError: Invalid type.
Reference example
Python
Output
Expected (from notebook):
The variable has not been assigned

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
name 'b' is not defined

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
division by zero
Please enter the denominator greater than 0

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
name 'b' is not defined
Main exception got caught here

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Example HCL
HCL
try:
    num=int(input("Enter a number"))
    result=10/num
except ValueError:
    print("This is not a valid number")
except ZeroDivisionError:
    print("enter denominator greater than 0")
except Exception as ex:
    print(ex)

Browser practice only — full example needs Python on your computer (files, Flask, threads, etc.).

Example HCL
HCL
## try,except,else block
try:
    num=int(input("Enter a number:"))
    result=10/num
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")
except Exception as ex:
    print(ex)
else:
    print(f"the result is {result}")

    

Browser practice only — full example needs Python on your computer (files, Flask, threads, etc.).

Example HCL
HCL
## try,except,else and finally
try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")
except Exception as ex:
    print(ex)
else:
    print(f"The result is {result}")
finally:
    print("Execution complete.")

Browser practice only — full example needs Python on your computer (files, Flask, threads, etc.).

Example HCL
HCL
### File handling and Exception HAndling

try:
    file=open('example1.txt','r')
    content=file.read()
    a=b
    print(content)

except FileNotFoundError:
    print("The file does not exists")
except Exception as ex:
    print(ex)

finally:
    if 'file' in locals() or not file.closed():
        file.close()
        print('file close')

Browser practice only — full example needs Python on your computer (files, Flask, threads, etc.).

Reference example
Python
Output
Expected (from notebook):
True

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Practice test — try yourself

Write code, press Check. Wrong answer shows the correct code to copy & run.

Try to divide 10 by 0. In except, print Cannot divide.

Python