×

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

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

How to print in the same line in Python?

How to print in the same line in python By default, the print function in Python takes us to the next line and prints the desired statement in the output. In this...

5 minutes read.

Curdir Python

Python Programming Language 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...

3 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.