0% found this document useful (0 votes)
14 views16 pages

Week 13 Topics

This comprehensive report explores error handling in programming, detailing various types of errors including syntax, semantic, runtime, and logical errors, along with their sources and handling techniques. It aims to provide developers, educators, and students with a thorough understanding of error management through practical examples and strategies for error recovery. The document concludes with insights into the importance of effective error handling in robust software development.

Uploaded by

PIRSALMAN SHAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views16 pages

Week 13 Topics

This comprehensive report explores error handling in programming, detailing various types of errors including syntax, semantic, runtime, and logical errors, along with their sources and handling techniques. It aims to provide developers, educators, and students with a thorough understanding of error management through practical examples and strategies for error recovery. The document concludes with insights into the importance of effective error handling in robust software development.

Uploaded by

PIRSALMAN SHAH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Error Handling in Programming: A Comprehensive

Report

May 5, 2025

Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Error Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.1 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Semantic Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Runtime Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Logical Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 Error Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1 Human Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Environmental Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3 External Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.4 Toolchain Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

4 Error Handling Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . 9


4.1 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 Return Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.3 Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.4 Input Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

5 Syntax and Semantic Error Recovery . . . . . . . . . . . . . . . . . . . . 14


5.1 Syntax Error Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5.2 Semantic Error Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

1
1 Introduction
Programming is inherently prone to errors due to its complexity, human involvement,
and environmental factors. This report provides an in-depth exploration of error types,
their sources, error handling techniques, and strategies for syntax and semantic error
recovery. Each topic is covered with detailed explanations and multiple practical examples
to illustrate real-world applications. The goal is to equip developers, educators, and
students with a thorough understanding of error management in programming.

2 Error Types
Errors in programming can be classified based on when they occur and their nature.
Understanding these types is crucial for effective debugging and robust software develop-
ment.

2.1 Syntax Errors


Syntax errors occur when code violates the grammatical rules of a programming language.
These are typically caught by compilers or interpreters during the parsing phase.
• Example 1: Missing Semicolon in C
1 # include < stdio .h >
2 int main () {
3 printf ( " Hello , World ! " ) // Missing semicolon
4 return 0;
5 }

The compiler reports a syntax error due to the missing semicolon after the printf
statement.
• Example 2: Incorrect Keyword in Python
1 def calculate_sum (a , b ) :
2 retrun a + b # Misspelled ’ return ’

Python raises a syntax error for the misspelled keyword retrun.


• Example 3: Unclosed Parenthesis in JavaScript
1 function greet ( name ) {
2 console . log ( " Hello , " + name ; // Missing closing
parenthesis
3 }

The JavaScript engine detects a syntax error due to the unclosed parenthesis.
• Example 4: Invalid Indentation in Python
1 def print_message () :
2 print ( " Hello ! " ) # Incorrect indentation

Python raises a syntax error because the print statement is not properly indented.

2
2.2 Semantic Errors
Semantic errors occur when code is syntactically correct but produces incorrect or unin-
tended behavior due to logical flaws.
• Example 1: Incorrect Loop Logic in Python
1 def factorial ( n ) :
2 result = 0 # Should be 1 for multiplication
3 for i in range (1 , n + 1) :
4 result *= i
5 return result
6 print ( factorial (5) ) # Outputs 0 , expected 120

The initialization of result to 0 causes the function to always return 0.


• Example 2: Wrong Operator in Java
1 public class Calculator {
2 public static int divide ( int a , int b ) {
3 return a - b ; // Should be a / b
4 }
5 public static void main ( String [] args ) {
6 System . out . println ( divide (10 , 2) ) ; // Outputs 8 ,
expected 5
7 }
8 }

Using subtraction instead of division leads to incorrect results.


• Example 3: Misused Variable in C++
1 # include < iostream >
2 int main () {
3 int x = 10;
4 int y = x ; // Intended to assign a different value
5 std :: cout << y << std :: endl ; // Outputs 10 , expected
another value
6 return 0;
7 }

The variable y is mistakenly assigned the value of x.


• Example 4: Incorrect Array Indexing in JavaScript
1 let numbers = [1 , 2 , 3];
2 let sum = numbers [3]; // Index out of bounds , should sum
elements
3 console . log ( sum ) ; // Outputs undefined , expected 6

Accessing an invalid index results in undefined instead of the intended sum.

3
2.3 Runtime Errors
Runtime errors occur during program execution, often due to invalid operations or exter-
nal conditions.
• Example 1: Division by Zero in Python
1 x = 10
2 y = 0
3 result = x / y # Raises ZeroDi vision Error

The program crashes with a ZeroDivisionError.


• Example 2: Null Pointer Exception in Java
1 public class Test {
2 public static void main ( String [] args ) {
3 String str = null ;
4 System . out . println ( str . length () ) ; //
N ul lP oi nt e r E x c e p t i o n
5 }
6 }

Accessing a method on a null object causes a NullPointerException.


• Example 3: File Not Found in C
1 # include < stdio .h >
2 int main () {
3 FILE * file = fopen ( " nonexistent . txt " , " r " ) ;
4 if (! file ) {
5 perror ( " Error opening file " ) ;
6 return 1;
7 }
8 return 0;
9 }

Attempting to open a nonexistent file results in a runtime error.


• Example 4: Array Index Out of Bounds in C++
1 # include < iostream >
2 int main () {
3 int arr [3] = {1 , 2 , 3};
4 std :: cout << arr [5] << std :: endl ; // Undefined behavior
5 return 0;
6 }

Accessing an out-of-bounds index causes undefined behavior.

2.4 Logical Errors


Logical errors result in incorrect output due to flawed program logic, despite correct
syntax and no runtime crashes.

4
• Example 1: Incorrect Formula in Python
1 def calculate_area ( radius ) :
2 return 3.14 * radius # Should be 3.14 * radius * radius
3 print ( calculate_area (5) ) # Outputs 15.7 , expected 78.5

The formula for the area of a circle is incorrect.


• Example 2: Wrong Conditional in JavaScript
1 function is_positive ( num ) {
2 if ( num > 0) {
3 return false ; // Should return true
4 }
5 return true ;
6 }
7 console . log ( is_positive (5) ) ; // Outputs false , expected true

The conditional logic is reversed.


• Example 3: Incorrect Loop Range in C
1 # include < stdio .h >
2 int main () {
3 int sum = 0;
4 for ( int i = 0; i <= 5; i ++) { // Should start from 1
5 sum += i ;
6 }
7 printf ( " % d \ n " , sum ) ; // Outputs 15 , expected 15 ( but logic
flawed for sum of 1 to 5)
8 return 0;
9 }

Including 0 in the sum may not align with the intended logic.
• Example 4: Miscalculated Tax in Java
1 public class TaxCalculator {
2 public static double calculateTax ( double income ) {
3 return income * 0.05; // Should include tiered rates
4 }
5 public static void main ( String [] args ) {
6 System . out . println ( calculateTax (50000) ) ; // Outputs
2500 , expected complex calculation
7 }
8 }

A flat tax rate oversimplifies the actual tax calculation.

3 Error Sources
Errors arise from various sources, ranging from human mistakes to environmental factors.
Identifying these sources helps in preventing and mitigating errors.

5
3.1 Human Error
Programmers often introduce errors due to inattention, lack of understanding, or incorrect
assumptions.
• Example 1: Typo in Variable Name (Python)
1 total = 100
2 print ( totla ) # Typo in variable name

A NameError occurs due to the misspelled variable totla.


• Example 2: Incorrect Assumption in Java
1 public class Average {
2 public static double calculateAverage ( int [] nums ) {
3 return nums [0] / nums . length ; // Assumes first element
represents sum
4 }
5 public static void main ( String [] args ) {
6 int [] nums = {1 , 2 , 3};
7 System . out . println ( calculateAverage ( nums ) ) ; // Outputs
0.333 , expected 2
8 }
9 }

The programmer incorrectly assumes the first element is the sum.


• Example 3: Misunderstood Requirement in C++
1 # include < iostream >
2 int main () {
3 int price = 50;
4 std :: cout << price * 0.9 << std :: endl ; // Applies discount
, but requirement was tax
5 return 0;
6 }

The code applies a discount instead of the required tax.


• Example 4: Copy-Paste Error in JavaScript
1 let user1 = { name : " Alice " , age : 25 };
2 let user2 = { name : " Alice " , age : 25 }; // Copied user1 ,
meant different user
3 console . log ( user2 . name ) ; // Outputs " Alice " , expected " Bob "

Copy-pasting leads to incorrect data for user2.

3.2 Environmental Issues


Hardware, operating systems, or network issues can cause errors.
• Example 1: Disk Full Error in Python

6
1 with open ( " large_file . txt " , " w " ) as f :
2 f . write ( " x " * 10**9) # May fail if disk is full

A full disk causes an IOError.


• Example 2: Network Failure in Java
1 import java . net . URL ;
2 import java . net . HttpU RLConn ection ;
3 public class NetworkTest {
4 public static void main ( String [] args ) throws Exception {
5 URL url = new URL ( " http :// example . com " ) ;
6 HttpUR LConne ction conn = ( HttpU RLConn ection ) url .
openConnection () ;
7 conn . getResponseCode () ; // Fails if network is down
8 }
9 }

A network outage results in an IOException.


• Example 3: Memory Limitation in C
1 # include < stdlib .h >
2 int main () {
3 int * arr = ( int *) malloc (1000000000 * sizeof ( int ) ) ; //
Excessive allocation
4 if (! arr ) {
5 printf ( " Memory allocation failed \ n " ) ;
6 return 1;
7 }
8 return 0;
9 }

Insufficient memory causes allocation failure.


• Example 4: OS-Specific Path Error in Python
1 file_path = " C :\ data \ file . txt " # Incorrect escape sequence
on Windows
2 with open ( file_path , " r " ) as f :
3 content = f . read ()

An invalid path causes a FileNotFoundError.

3.3 External Inputs


Invalid or unexpected inputs from users or external systems can lead to errors.
• Example 1: Invalid User Input in Python
1 age = int ( input ( " Enter your age : " ) ) # User enters " abc "

A ValueError occurs if the input cannot be converted to an integer.

7
• Example 2: Malformed JSON in JavaScript
1 let data = JSON . parse ( ’ {" name ": " Alice " ’) ; // Missing
closing brace

A SyntaxError is raised due to invalid JSON.


• Example 3: Corrupted File in C
1 # include < stdio .h >
2 int main () {
3 FILE * file = fopen ( " corrupted . bin " , " rb " ) ;
4 int data ;
5 fread (& data , sizeof ( int ) , 1 , file ) ; // Corrupted data
causes issues
6 fclose ( file ) ;
7 return 0;
8 }

Reading corrupted data may lead to incorrect behavior.


• Example 4: Unexpected API Response in Python
1 import requests
2 response = requests . get ( " http :// api . example . com / data " )
3 data = response . json () [ " key " ] # Key may not exist

A KeyError occurs if the expected key is missing.

3.4 Toolchain Issues


Bugs in compilers, interpreters, or libraries can introduce errors.
• Example 1: Compiler Bug in C
1 # include < stdio .h >
2 int main () {
3 int x = 1 << 31; // May cause issues in some compilers
4 printf ( " % d \ n " , x ) ;
5 return 0;
6 }

A buggy compiler might mishandle large bit shifts.


• Example 2: Library Bug in Python
1 import buggy_library # Hypothetical buggy library
2 result = buggy_library . compute (5) # Unexpected behavior

A bug in the library causes incorrect results.


• Example 3: Interpreter Issue in JavaScript
1 let x = 0.1 + 0.2; // Floating - point precision issue
2 console . log ( x ) ; // Outputs 0. 3 0 00 0 0 00 0 0 00 0 0 00 4

8
The JavaScript engines floating-point handling introduces errors.
• Example 4: Linker Error in C++
1 # include < iostream >
2 extern int undef in ed _f un ct io n () ; // Missing implementation
3 int main () {
4 undefined_fun ct io n () ;
5 return 0;
6 }

The linker fails due to an undefined function.

4 Error Handling Techniques


Effective error handling ensures programs are robust and user-friendly. Below are key
techniques with examples.

4.1 Exception Handling


Exception handling uses try-catch blocks to manage errors gracefully.
• Example 1: Division by Zero in Python
1 try :
2 x = 10 / 0
3 except ZeroDi vision Error as e :
4 print ( f " Error : { e } " )

The program catches the ZeroDivisionError and prints an error message.


• Example 2: File Handling in Java
1 import java . io . File ;
2 import java . io . FileReader ;
3 public class FileTest {
4 public static void main ( String [] args ) {
5 try {
6 FileReader reader = new FileReader ( " missing . txt " ) ;
7 } catch ( java . io . F i l e N o t F o u n d E x c e p t i o n e ) {
8 System . out . println ( " File not found : " + e . getMessage () )
;
9 }
10 }
11 }

The FileNotFoundException is handled gracefully.


• Example 3: Type Conversion in C++
1 # include < iostream >
2 # include < stdexcept >
3 int main () {

9
4 try {
5 throw std :: invalid_argument ( " Invalid input " ) ;
6 } catch ( const std :: invalid_argument & e ) {
7 std :: cout << " Caught : " << e . what () << std :: endl ;
8 }
9 return 0;
10 }

A custom exception is thrown and caught.


• Example 4: JSON Parsing in JavaScript
1 try {
2 let data = JSON . parse ( ’ {" invalid "} ’) ;
3 } catch ( e ) {
4 console . log ( " Parsing error : " , e . message ) ;
5 }

The SyntaxError from invalid JSON is caught.

4.2 Return Codes


Functions return specific codes to indicate success or failure.
• Example 1: File Open in C
1 # include < stdio .h >
2 int main () {
3 FILE * file = fopen ( " data . txt " , " r " ) ;
4 if (! file ) {
5 printf ( " Failed to open file \ n " ) ;
6 return 1;
7 }
8 fclose ( file ) ;
9 return 0;
10 }
11 \ vender
12 The null pointer return indicates failure .
13

14 \ item \ textbf { Example 2: Memory Allocation in C ++}


15 \ begin { lstlisting }[ language = C ++]
16 # include < iostream >
17 int * allocate_array ( int size ) {
18 int * arr = new ( std :: nothrow ) int [ size ];
19 return arr ;
20 }
21 int main () {
22 int * arr = allocate_array (1000) ;
23 if (! arr ) {
24 std :: cout << " Allocation failed " << std :: endl ;
25 return 1;
26 }

10
27 delete [] arr ;
28 return 0;
29 }

A null pointer indicates allocation failure.


• Example 3: Socket Connection in Python
1 import socket
2 def connect ( host , port ) :
3 s = socket . socket ()
4 try :
5 s . connect (( host , port ) )
6 return 0
7 except :
8 return -1
9 if connect ( " example . com " , 80) == -1:
10 print ( " Connection failed " )

A negative return code signals failure.


• Example 4: Database Query in Java
1 import java . sql . Connection ;
2 public class Database {
3 public int executeQuery ( Connection conn , String query ) {
4 try {
5 conn . createStatement () . execute ( query ) ;
6 return 0;
7 } catch ( Exception e ) {
8 return -1;
9 }
10 }
11 }

A return code of -1 indicates a query error.

4.3 Logging
Logging records errors for debugging and monitoring.
• Example 1: Python Logging
1 import logging
2 logging . basicConfig ( filename = " app . log " , level = logging . ERROR )
3 try :
4 x = 1 / 0
5 except ZeroDi vision Error as e :
6 logging . error ( " Division error : % s " , e )

The error is logged to app.log.


• Example 2: Java Logging

11
1 import java . util . logging . Logger ;
2 import java . util . logging . FileHandler ;
3 public class LogTest {
4 public static void main ( String [] args ) throws Exception {
5 Logger logger = Logger . getLogger ( " MyLog " ) ;
6 logger . addHandler ( new FileHandler ( " app . log " ) ) ;
7 try {
8 int x = 1 / 0;
9 } catch ( Ari t h me t i cE x c ep t i on e ) {
10 logger . severe ( " Error : " + e . getMessage () ) ;
11 }
12 }
13 }

The arithmetic error is logged.


• Example 3: JavaScript Console Logging
1 try {
2 let x = undefinedVar ;
3 } catch ( e ) {
4 console . error ( " Error occurred : " , e . message ) ;
5 }

The error is logged to the console.


• Example 4: C++ Custom Logging
1 # include < fstream >
2 # include < iostream >
3 void log_error ( const std :: string & msg ) {
4 std :: ofstream log ( " app . log " , std :: ios :: app ) ;
5 log << " Error : " << msg << std :: endl ;
6 }
7 int main () {
8 try {
9 throw std :: runtime_error ( " Test error " ) ;
10 } catch ( const std :: runtime_error & e ) {
11 log_error ( e . what () ) ;
12 }
13 return 0;
14 }

The error is appended to a log file.

4.4 Input Validation


Validating inputs prevents errors from malformed data.
• Example 1: Python Input Validation
1 def process_age ( age_str ) :

12
2 if not age_str . isdigit () :
3 raise ValueError ( " Age must be a number " )
4 age = int ( age_str )
5 if age < 0 or age > 120:
6 raise ValueError ( " Invalid age range " )
7 return age
8 try :
9 print ( process_age ( " abc " ) )
10 except ValueError as e :
11 print ( e )

Invalid input raises a ValueError.


• Example 2: Java Input Validation
1 public class Validator {
2 public static int validateAge ( String ageStr ) throws
Exception {
3 try {
4 int age = Integer . parseInt ( ageStr ) ;
5 if ( age < 0 || age > 120) {
6 throw new Exception ( " Invalid age range " ) ;
7 }
8 return age ;
9 } catch ( Nu m b e r F o r m a t E x c e p t i o n e ) {
10 throw new Exception ( " Age must be a number " ) ;
11 }
12 }
13 public static void main ( String [] args ) {
14 try {
15 validateAge ( " abc " ) ;
16 } catch ( Exception e ) {
17 System . out . println ( e . getMessage () ) ;
18 }
19 }
20 }

The input is validated for type and range.


• Example 3: JavaScript Input Validation
1 function validateEmail ( email ) {
2 const re = /^[^\ s@ ]+ @ [^\ s@ ]+\.[^\ s@ ]+ $ /;
3 if (! re . test ( email ) ) {
4 throw new Error ( " Invalid email format " ) ;
5 }
6 return email ;
7 }
8 try {
9 validateEmail ( " invalid_email " ) ;
10 } catch ( e ) {
11 console . log ( e . message ) ;
12 }

13
A regular expression validates the email format.
• Example 4: C Input Validation
1 # include < stdio .h >
2 # include < string .h >
3 int validate_input ( char * input ) {
4 for ( int i = 0; input [ i ]; i ++) {
5 if (! isdigit ( input [ i ]) ) {
6 return 0;
7 }
8 }
9 return 1;
10 }
11 int main () {
12 char input [10];
13 scanf ( " % s " , input ) ;
14 if (! validate_input ( input ) ) {
15 printf ( " Invalid input \ n " ) ;
16 } else {
17 printf ( " Valid number \ n " ) ;
18 }
19 return 0;
20 }

The input is checked for digits only.

5 Syntax and Semantic Error Recovery


Error recovery allows compilers, interpreters, or programs to continue processing despite
errors, providing useful feedback or partial functionality.

5.1 Syntax Error Recovery


Syntax error recovery enables parsers to continue analyzing code after detecting errors.
• Example 1: Panic Mode Recovery in C
1 # include < stdio .h >
2 int main () {
3 printf ( " Hello " // Missing semicolon , parser skips to next
line
4 int x = 10;
5 printf ( " % d \ n " , x ) ;
6 return 0;
7 }

The compiler skips the erroneous line and continues parsing.


• Example 2: Phrase-Level Recovery in Python

14
1 def add (a , b )
2 return a + b # Missing colon , IDE suggests adding it

An IDE like PyCharm inserts a colon to fix the syntax.


• Example 3: Error Productions in Java
1 public class Test {
2 public static void main ( String [] args ) {
3 int x = 5 // Missing semicolon , compiler reports and
continues
4 int y = 10;
5 System . out . println ( y ) ;
6 }
7 }

The compiler uses error productions to report the missing semicolon.


• Example 4: Global Correction in JavaScript
1 function test () {
2 console . log ( " Test " // Missing parenthesis , IDE suggests
fix
3 }

The IDE suggests adding a closing parenthesis to balance the expression.

5.2 Semantic Error Recovery


Semantic error recovery mitigates logical errors to allow partial execution or compilation.
• Example 1: Type Inference in Python
1 x = "5" + 3 # Type mismatch , IDE suggests str (3)
2 print ( x )

The IDE suggests converting the integer to a string.


• Example 2: Symbol Table Adjustment in C++
1 # include < iostream >
2 int main () {
3 cout << x << endl ; // Undeclared variable , assume int
4 return 0;
5 }

A compiler might assume x is an int and issue a warning.


• Example 3: Default Behavior in Java
1 public class Fallback {
2 public static int getValue ( String input ) {
3 try {
4 return Integer . parseInt ( input ) ;

15
5 } catch ( Nu m b e r F o r m a t E x c e p t i o n e ) {
6 return 0; // Default value
7 }
8 }
9 public static void main ( String [] args ) {
10 System . out . println ( getValue ( " abc " ) ) ; // Outputs 0
11 }
12 }

A default value is returned on error.


• Example 4: Static Analysis in JavaScript
1 function unused () {
2 let x = 10; // Unused variable , linter warns
3 }

ESLint flags the unused variable, allowing the programmer to fix it.

6 Conclusion
This report has provided a comprehensive analysis of error types, sources, handling tech-
niques, and recovery strategies in programming. By understanding these concepts and
applying the demonstrated techniques, developers can build robust, reliable software. The
examples across multiple languages highlight practical applications, ensuring relevance
for diverse programming contexts.

16

You might also like