Chapter 1
Chapter 1
Syntax Errors:
• Syntax errors occur when we have not followed the rules/syntax of a particular
programming language while writing a program. These are grammatical mistakes made.
• Examples of syntax errors include missing parenthesis, quotation marks etc.
Exception
• Exception is an unexpected event that occurs during the execution of a program. It is an
error that occurs during runtime.
• Exception is a python object that represents an error. Even if the statement is syntactically
correct, there might be a situation in which an exception may occur.
• Examples are dividing by O, accessing a variable without defining it, trying to open a non-
existing file.
• Commonly occurring exceptions are usually defined in the compiler/interpreter. These are
called built-in exceptions.
• The programmer then has to take appropriate action to handle the exception.
SyntaxError: Raised when there is a mistake in the syntax of the Python code.
Example: print("Hello, world!"
A SyntaxError will be raised because the closing parenthesis is missing.
ValueError: Occurs when a function gets the correct type of argument but with an invalid value.
Example: int("Hello")
This will raise a ValueError because the string "Hello" cannot be converted into an
integer due to the presence of non-numeric characters.
KeyboardInterrupt: Triggered when the user interrupts program execution, such as by pressing
Delete or Esc.
Example: while True:
pass # Infinite loop
If you run this, the program will keep running indefinitely. When you press Ctrl+C, a
KeyboardInterrupt will be raised, stopping the program.
ImportError: Raised when a module definition cannot be found during an import operation.
Example: import scientific_maths
If the module scientific_maths does not exist, you will encounter an ImportError.
import math as m
print(m.exp(1000))
EOFError: Occurs when input() reaches the end of a file without reading any data.
Example: input("Enter a number: ")
It will raise an EOFError when the input() function reaches the end of the file without
reading any data.
ZeroDivisionError: Raised when a operation is attempted with zero denominator. division as the
Example: div = 10/0
This line attempts to divide 10 by 0, which is not allowed in math, ZeroDivisionError.
SO Python raises a
IndexError: Occurs when trying to access an index that is out of range in a sequence like a list or
tuple.
Example: list1 = [1, 2, 3, 4, 5]
print(list1[10])
When you try to access list1 [10],it results in an IndexError because there is no
element at that index.
OverflowError: Raised when the result of a calculation is too large for the data type to handle.
Example: import math result = math.exp(1000)
In this example, the math.exp(1000) function tries to compute e1000, which is too
large to represent as a floating-point number, leading to an OverflowError.
Raising exceptions
• Exceptions handlers are designed to execute when a specific exception is raised.
• Programmers can also forcefully raise exceptions in a program using the raise and assert
statement in the current block of code is executed.
• So, raising an exception involves interrupting the normal flow execution of program and
jumping to that part of the program which is written to handle such exceptional situations.
In Python raise keyword is used to raise exceptions or errors.
The raise keyword raises an error and stops the control flow of the program.
Syntax:
raise exception_name [(optional argment)]
The argument is generally a string that is displayed when the exception is raised.
Example:
a=5
if a % 2! = 0
raise exception ("the number should not be an odd integer")
Use of the raise statement to throw exception
Index Error
Python an index error means that when a code is trying to access an index that because the index
goes out of bounds by being too large.
Stack traceback
Stack traceback is a structured block of text that contains information about the sequence of
function calls that have been mode in the branch of execution of code in which the
exception was raised.
Assert statement
An assert statement in python is used to test an expression in the program code. If the result after
testing comes false, then the exception is raised. This statement is generally used in the beginning
of the function or after a function call to check for valid input.
OR
Assertion are simply Boolean expression that check if the condition return true or not. If it is true,
the program does nothing and moves to the next line of code. If it is false the program stops
and throws an error.
Example:
EXCEPTION HANDLING:
Exception Handling is a programming technique used to detect and manage errors that occur
during the execution of a program.
By writing additional code in a program to give proper messages or instructions to the user on
encountering an exception. This process is known as exception handling.
When a function is called, it is added to the top of the stack, and when the function finishes
executing, it is removed from the stack.
Catching the Exception: When a suitable handler is found, the runtime system executes that
handler. This process is known as "catching the exception."
Ending Program Execution: If the runtime system cannot find any suitable handler after searching
all methods in the call stack, the program will stop running.
Example:
def divide(a, b):
return a/b
def calculate():
try:
result = divide(10, 0)
except ZeroDivisionError:
print("Cannot divide by zero!")
calculate()
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Explanation:
• try block asks for user input and tries to divide 100 by the input number.
• except blocks handle ZeroDivisionError and ValueError.
• else block runs if no exception occurs, displaying the result.
• finally block runs regardless of the outcome, indicating the completion of execution.
• Statements that may cause exceptions are kept in try block and those that handle them are
kept in A except block.
Catching Exception
• An exception is said to be caught when a code that is designed to handle a particular
exception is executed.
• Exceptions, if any, are caught in the try block and handled in the except block.
• While executing the program, if an exception is encountered, further execution of the code
inside the try block is stopped and the control is transferred to the except block.
try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
Finally Clause:
• Finally block is always executed regardless of whether an exception has occurred or not.
• Finally block should always be placed at the end of try clause, after all except blocks
and the else block.