Python Errors and exceptions
Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two similar yet different words.
Errors are of two types – syntax errors and logical errors. Errors generally occur at the compilation time due to the programmer's mistake. Syntactical errors occur when the programmer misses following the syntax rules, whereas logical errors occur when he makes a mistake in the logic of the code. Logical errors are not raised but are found when the output is incorrect. On the other hand, when a syntax error occurs, the interpreter will not execute the program.
Exceptions, on the other hand, are runtime errors. These occur at the run time. When exceptions are raised, the normal flow of the program will not be stopped, but altered and disturbs the whole flow of the program and sometimes terminates at the statement with an exception.
Syntax errors
Every single entity or a statement in Python has its predefined syntax. It is like the spelling of words in English. If we make a mistake in the spelling, it is no longer a correct word. In the same way, if we do not follow the syntax rules in Python, the statement is not correct. A syntax error is raised, and the program execution halts.
Syntax error can occur when:
- The syntax of statements is not followed
- Due to a missing colon
- Wrong indentation
- Missing a required keyword
- Misspelling a keyword or the name of a method.
Example code:
1. #Missing colon in if statement
a = int (input ("Enter the value of a: "))
if (a%2 == 0)
# if (a%2 == 0): -> correct use -> colon
print (a, "is an even number")
else:
print (a, "is not an even number")
Output:
File "D:\Programs\python\syntaxerror1.py", line 2
if (a%2 == 0)
^
SyntaxError: invalid syntax
2. #Wrong indentation
a = int (input ("Enter the value of a: "))
if (a%2 == 0):
print (a, "is an even number")
#print (a, “is an even number”) -> correct indentation
else:
print (a, "is not an even number")
Output:
File "D:\Programs\python\syntaxerror2.py", line 3
print (a, "is an even number")
^
IndentationError: expected an indented block.
3. #Misspelling a keyword (if)
a = int (input ("Enter the value of a: "))
iff (a%2 == 0): #if -> correct spelling
print (a, "is an even number")
else:
print (a, "is not an even number")
Output:
File "D:\Programs\python\syntaxerror3.py", line 2
iff (a%2 == 0):
^
SyntaxError: invalid syntax
4. #Missing a keyword (if)
a = int (input ("Enter the value of a: "))
(a%2 == 0): #if (a%2==0) -> if keyword is missed
print (a, "is an even number")
else:
print(a, "is not an even number")
Output:
File "D:\Programs\python\syntaxerror4.py", line 2
(a%2 == 0):
^
SyntaxError: invalid syntax
5. #Syntax not followed
All the above conditions come under syntax not followed too.
a = int (input ("Enter the value of a: "))
if: #if (condition): -> correct syntax
print (a, "is an even number")
else:
print(a, "is not an even number")
Output:
File "D:\Programs\python\syntaxerror5.py", line 2
if:
^
SyntaxError: invalid syntax
Understanding:
Here, we missed the condition for the if statement.
Logical Errors
After passing the syntax test, if the code is not giving the accurate and expected output, it means it is flawed and there is a logical error. These errors are not detected. The programmer needs to use different sample test cases to check if the logic is right and the result is correct. Finding logical errors can be very hard in vast and complicated codes. Finding such huge bugs after writing the code is called debugging.
These occur when the program runs without crashing but produces an incorrect result.
These types of errors can occur due to:
- Using the wrong variable name
- Flawed indentation
- Using integer division where floating-point division is to be used.
- Not verifying operator precedence, etc.
Examples:
1. #Using wrong variable name
a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
sum = a + b
print ("The sum of a and b is", a);
#print ("The sum of a and b is", sum); -> correct variable name
Output:
Expected output:
Enter the first number: 20
Enter the second number: 30
The sum of a and b is 50
Observed output due to the use of a in the place of sum:
Enter the first number: 20
Enter the second number: 30
The sum of a and b is 20
2. #Flawed indentation
a = int (input ("Enter the value of a: "))
if (a%2 == 0):
print (a)
print ("is an even number")
#print (“is an even number”) -> correct indentation
if (a%2!=0):
print(a, "is not an even number")
Output:
Expected output:
Enter the value of a: 5
5 is not an even number
Observed output due to flawed indentation of the print statement after the first if statement:
Enter the value of a: 5
is an even number
5 is not an even number
3. # using integer division where floating-point division is to be used.
a = float (input ("Enter the value of a: "))
b = float (input ("Enter the value of b: "))
print (a//b)
#print (a/b) -> correct use -> floating point division
Output
Expected output:
Enter the value of a: 4
Enter the value of b: 5.6
0.7142857142857143
Observed output due to use of integer division when we want float quotient
Enter the value of a: 4
Enter the value of b: 5.6
0.0
4. #Not checking operator precedence
a = int (input ("Enter the value of a: "))
b = int (input ("Enter the value of b: "))
print (a/ b+3)
#print (a/ (b+3)) -> correct use of operators.
Output:
Expected output:
Enter the value of a: 4
Enter the value of b: 3
0.6666666666666666
Observed output:
Enter the value of a: 4
Enter the value of b: 3
4.333333333333333
Exceptions
Exceptions are run time errors, which mean that the code has passed the syntax test, and when the interpreter runs it, it is crashed unexpectedly due to some internal problem in the code that is not detected at the start. The interpreter will crash the program once it reaches the line with the error.
Such programs work well for some sample test cases, but the program might get crashed for some. Hence, we need to consider every possible set of inputs for the program and check.
Exceptions can occur when:
- We try to divide by 0
- We try to do operations on incompatible data type variables
- We try to access a variable that is not defined
- We try to access an index in a list or a dictionary that does not exist
- We try to access an un-existing file.
Note: The program will be executed until the line with the exception and crashes once the line is reached, unlike errors where the program won't execute.
Examples:
1. #Division by zero
a = int (input ("Enter the value of a: "))
b = int (input ("Enter the value of b: "))
print (a/b)
Output:
Enter the value of a: 4
Enter the value of b: 0
Traceback (most recent call last):
File "D:\Programs\python\divisionby0.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
2. #Operations on incompatible datatypes
a = int (input ("Enter the value of a: "))
b = input ("Enter the value of b: ") #string
print (a/b)
Output:
Enter the value of a: 4
Enter the value of b: 3
Traceback (most recent call last):
File "D:\Programs\python\uncompatibility.py", line 3, in <module>
print(a/b)
TypeError: unsupported operand type(s) for /: 'int' and 'str'
3. #Accessing an undefined variable
a = int (input ("Enter the value of a: "))
print (a/b)
Output:
Enter the value of a: 3
Traceback (most recent call last):
File "D:\Programs\python\undefined.py", line 2, in <module>
print (a/b)
NameError: name 'b' is not defined
4. # Accessing a no existing index in a list
a = [1, 2, 3]
print ("The list is: ",a)
print (a[3])
Output:
The list is: [1, 2, 3]
Traceback (most recent call last):
File "D:\Programs\python\index.py", line 3, in <module>
print (a[3])
IndexError: list index out of range
5. #Accessing a file that does not exist
print ("opening a non existing file")
file1 = open ("textfile.txt")
print(file1.read())
file1.close()
Output:
opening a non-existing file
Traceback (most recent call last):
File "D:\Programs\python\nofile.py", line 2, in <module>
file1 = open ("textfile.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'textfile.txt'
These are some common situations the programmer might run into errors and exceptions. Errors and exceptions need to be handled after finding, and Python has a special process to handle exceptions. Using try and except blocks, we can handle unexpected exceptions. The concept is called Exception handling.