Explain Errors and Exceptions in Python

Explain Errors and Exceptions in Python

 Errors and Exceptions in Python

Errors are issues in a program that lead to the termination of its execution. Conversely, exceptions are triggered by internal events that disrupt the regular flow of the program.

Two Types of Errors Can Occur in Python.

  1. Syntax errors
  2. Logical errors (Exceptions)

1. Syntax errors

When the proper syntax of the language is not followed at that time a syntax error is thrown.

Example:


# Initialize the amount variable
purchase_amount = 100
# Check if you are eligible to purchase DSA Self Paced or not
if (purchase_amount > 299)
print("You are eligible to purchase item under 299")

Output:

ERROR!
File “<string>”, line 5
if (purchase_amount > 299)
^
SyntaxError: expected ‘:’

The error message appears because we forgot to put a colon (:) after the ‘if’ statement. We can correct this by adding the missing colon to the syntax.

Save $100 in the next
5:00 minutes?

Register Here

2. logical errors(Exception)

When an error happens during the program’s execution, even after passing the syntax check, it’s called an exception or a logical error. For instance, if we try to divide a number by zero, it raises the ZeroDivisionError exception. Similarly, importing a module that doesn’t exist triggers an ImportError.

Example 1:


# initialize the amount variable
marks = 100
# perform division with 0
result = marks / 0
print(result)

Output:

ERROR!
Traceback (most recent call last):
File “<string>”, line 5, in <module>
ZeroDivisionError: division by zero
In the example above, the ZeroDivisionError occurs because we are attempting to divide a number by 0.

Example 2: When indentation is not correct.


if (a < 3):
print("gfg")

Output:

Traceback (most recent call last):
File “<string>”, line 1, in <module>
ERROR!
NameError: name ‘a’ is not defined

Some additional common built-in exceptions, aside from the ones mentioned above, include:

  1. IndexError: When attempting to retrieve an index that doesn’t exist in a list.
  2. AssertionError: It happens when the assert statement does not hold true.
  3. AttributeError: It happens when there is a failure in assigning an attribute.
  4. ImportError: It happens when a required module for import is not found.
  5. KeyError: It happens when attempting to access a key in a dictionary that does not exist.
  6. NameError: It happens when trying to use a variable that has not been defined.
  7. MemoryError: It happens when a program exhausts its available memory.
  8. TypeError: It happens when a function and operation are applied to an incorrect data type.

Save $100 in the next
5:00 minutes?

Register Here

Error Handling

When something goes wrong in a program, like an error or an exception, we use a method called ‘Handling’ to deal with and manage those issues.

Handling Exceptions with Try/Except/Finally

We manage errors using the Try/Except/Finally method. In the ‘try’ block, we write the code that might cause issues. If there’s an issue, the ‘except’ block contains the fallback code. The ‘finally’ block includes code that runs regardless of whether there’s an error or not.

Example:


#operation in try block
try:
print("code started")
# unsafe operation perform
print(100 / 0)
# if error occur the it goes in except block
except:
print("an error occurs in code")
# final code in finally block
finally:
print("print finally block")

Output:

code started
an error occurs in code
print finally block

Creating Exceptions When A Predefined Condition

If we need to handle specific situations in our code due to certain limitations or conditions, we can use exception handling.

Example:


# try for unsafe code
try:
amount_data = 19
if amount_data < 299:
# raise the ValueError
raise ValueError("please add the money in your account")
else:
print("You are eligible to purchase item under 299")
# if false then raise the value error
except ValueError as e:
print(e)

Output:

please add the money in your account

Conclusion

Errors and exceptions are fundamental concepts in Python programming, providing mechanisms to handle unforeseen situations and ensuring smoother program execution.

Save $100 in the next
5:00 minutes?

Register Here