Chapter 04d · Computer Science
17 blocks · bilingual

Programming In Python - 4.4 Error Handling

LiveBilingual master notes · switch to नेपाली for the full glossary

Complete bilingual study notes for Programming In Python - 4.4 Error Handling — every concept explained step by step, with definitions, formulas, and worked examples.

4.5 Error Handling

Error handling in Python is a technique used to manage and handle errors or unexpected situations that occur while a program is running, so the program doesn't crash and can handle problems gracefully. Errors cause a program to stop running, while exceptions are special kinds of errors that can be handled during the program's execution.

try-except Block

A try-except block is used to catch and handle exceptions (errors) so the program can continue running smoothly.

Flowchart of Python error handling showing the try block, except block (on error), else block (if no error), and finally block (always runs).

try: # code that might cause an error except: # code to run if an error occurs

try: num = int(input("Enter a number: ")) print(100 / num) except: print("An error occurred. Please enter a valid number.")

Multiple except Blocks

Different except blocks can handle different types of exceptions.

try: num1 = int(input("Enter a number: ")) print(100 / num1) except ZeroDivisionError: print("You cannot divide by zero.") except ValueError: print("Please enter a valid number.") except: print("Something went wrong.")

else and finally

  • The else block runs only when no error occurs in the try block.
  • The finally block always runs, whether an error occurs or not — often used to close files or print closing messages.

try: num = int(input("Enter a number: ")) print(100 / num) except: print("An error occurred.") finally: print("Program ended.")

Handling Blank Input

A blank input error happens when the user presses Enter without typing any value. Python's input() function captures an empty string "". This can be checked using an if statement and handled by raising a ValueError inside a try-except block, or by using a validation loop.

try: value = input("Enter a number: ") if value == "": raise ValueError("Blank input is not allowed.") number = int(value) print("Number entered is:", number) except ValueError as e: print(e)