Error
An error is a problem in a program that stops its execution. Errors occur when the programmer writes invalid code or
logic that the interpreter cannot understand. In Python, these errors are detected at compile-time (syntax errors) or run-
time (logical or runtime errors).
Types of Errors in Python
1. Syntax Errors
Occur when the Python interpreter finds code that does not follow the correct grammar or structure of the Python
language.
Example:
print("Hello World" # missing closing parenthesis
Output:
SyntaxError: unexpected EOF while parsing
2. Runtime Errors
Occur while the program is running. The code is syntactically correct, but an unexpected condition occurs that the
program cannot handle.
Example:
x = 10 / 0
Output:
ZeroDivisionError: division by zero
3. Logical Errors
The syntax is correct, and the program runs successfully, but it produces an incorrect result due to flawed logic.
Example:
def add(a, b):
return a - b # logic error (should be a + b)
print(add(5, 3))
Output:
2 (Incorrect result)
Errors prevent the program from running successfully. However, not all errors should terminate execution — some can
be managed. This is where exceptions come into play.
Exception
An exception is a special type of error that occurs during program execution but can be anticipated and handled using
Python’s built-in mechanisms.
When an exception occurs, Python generates an exception object that contains details about the error. If this exception is
not handled properly, the program stops and displays an error message (traceback).
Example:
num = int(input("Enter a number: "))
print(10 / num)
If the user inputs 0, it will raise a ZeroDivisionError.
Instead of crashing, the program can handle this gracefully using exception handling techniques.
Error vs Exception
Basis Error Exception
Definition Problems in the code that prevent execution. Events detected during execution that can be handled.
Occurrence At compile-time (before execution). At runtime (during execution).
Handling Cannot be resolved or handled easily. Can be caught and managed using try-except blocks.
Example SyntaxError, IndentationError. ZeroDivisionError, ValueError, FileNotFoundError.
Cause Wrong syntax or invalid language usage. Invalid operations or input values.
Example Comparison:
# Error Example
print("Hello" # SyntaxError
# Exception Example
a = 10 / 0 # Raises ZeroDivisionError
While errors stop the program completely, exceptions can be controlled and managed smartly.
Exception Handling in Python
Exception Handling refers to the process of responding to the occurrence of exceptions without terminating the
program.
Python uses special keywords for handling exceptions, namely:
• try
• except
• else
• finally
• raise
The basic idea is to “try” a block of code that may cause an exception. If an exception occurs, control jumps to the
“except” block to manage it.
Try and Except
The try block contains the code that may raise an exception. The except block handles that exception if it occurs.
Basic syntax:
try:
# risky operation
except:
# exception handling code
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except:
print("Error occurred! Division by zero or invalid input.")
If the user inputs 0 or a non-integer value, the code in the except block executes, and the program continues running
smoothly.
Multiple Except Blocks
A single try block can handle multiple exceptions with separate except clauses. This allows the program to respond
differently to different types of errors.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a numeric value.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print("An unexpected error occurred:", e)
else:
print("Division successful! Result:", result)
In this code:
• ValueError occurs if a user enters non-numeric input.
• ZeroDivisionError occurs for zero input.
• The general Exception block handles all other unexpected errors.
Try - Except - Else
The else block runs only if no exception occurs in the try block. It is useful to place code that should execute after
successful execution of try block.
Example:
try:
num = int(input("Enter a number greater than zero: "))
result = 10 / num
except ZeroDivisionError:
print("Division by zero not allowed.")
except ValueError:
print("Please enter proper number.")
else:
print("Division successful! Result =", result)
If the block under “try” works fine, only then the “else” part executes. If the exception occurs, the else block is skipped.
Raise Keyword
The raise keyword is used to manually trigger an exception. It is usually used for validating inputs or specific situations
where a programmer wants to stop execution.
Example:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
else:
print("Your age is valid.")
Here, even though the code is syntactically correct, the programmer deliberately raises an error condition if the input is
invalid.
It can also re-raise existing exceptions:
try:
x = 1 / 0
except ZeroDivisionError:
raise
This helps to propagate exceptions after partial handling.
Finally Block
The finally block always runs, regardless of whether an exception occurred or not. It is often used to perform clean-up
tasks such as closing a file, releasing system resources, or ending database connections.
Example:
try:
file = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
print("Closing file (if open)...")
try:
[Link]()
except:
pass
Output possibilities:
• If the file exists, the content is read, and finally still runs.
• If the file doesn’t exist, only the except executes—but finally runs regardless.
The finally block is crucial for resource management.
Example: Handling User Input
def divide_numbers():
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Please enter numeric values only.")
else:
print("Result:", result)
finally:
print("Program execution complete.")
divide_numbers()