×

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:

  1. The syntax of statements is not followed
  2. Due to a missing colon
  3. Wrong indentation
  4. Missing a required keyword
  5. 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:

  1. Using the wrong variable name
  2. Flawed indentation
  3. Using integer division where floating-point division is to be used.
  4. 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:

  1. We try to divide by 0
  2. We try to do operations on incompatible data type variables
  3. We try to access a variable that is not defined
  4. We try to access an index in a list or a dictionary that does not exist
  5. 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.


Related Topics

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Python String upper() method

Python String upper() method The string.upper() method in Python returns a copy of the string converted to uppercase. Syntax string.upper() Parameter NA Return This method returns a copy of the string converted to uppercase. Example 1 # Python...

1 minute read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Python List insert() method

Python List insert() method The list.insert () method in Python inserts an item at the specified position. Syntax list.insert(i, x) Parameter i: This parameter represents a number specifying the position to insert the given value. x: This parameter signifies...

1 minute read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

PyShark in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.