×

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

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.

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 Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 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 exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players The object of Keyboard Jump (hop) Game Python Project is to fabricate...

7 minutes read.

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

3 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

How to Import Files in 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....

3 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.