Python Errors and Exceptions

What is an error?

An error is a condition that happens when the developer does not follow a suitable mechanism.

What is an exception?

These are only the sensible bugs that were found during run time. Like this, if the code is compiled (or) interpreted, the function turns out to be emphatical. Be that as it may, before long, at run time we can find expectations. These are just exceptions. Division with zero is a case of an exception.

Built-In Exceptions
Exception Class Event
I/O errors It increases when the input/ output function fails.
Arithmetic error It increases when the mathematical evaluation fails.
Floating-point error It increases when the floating-point evaluation fails.
Zero division error It increases while the division and modulo by zero happen.
Assertion error It increases when the assert declaration fails.
Overflow error It increases when the arithmetic function is too high.
Import error It increases while the imported module is not discovered.
Keyboard interrupt error It increases when the client interrupts the phase implementation. It is generally was completed by clicking Ctrl+c.
Stop iteration error It increases while the next technique of the iterator does not chance to some object.
Indentation error It increases while there is a wrong indentation.
Name error It increases while the identifier is not discovered in the local and global namespace.
Key error It increases when the defined key is not discovered in the dictionary.
Value error It increases when the function gets parameters of the right type but improper value.
Attribute error It increases while the attribute reference and assignment fails.
Syntax error It increases through the parser while the syntax bug is encountered.
Index error It increases while the index is out of range.
Runtime error It increases when the generated bug does not fall into any group.
Type error It increases when the function is used to the object of the incorrect type.
Unbound local error It increases while we are attempting to approach the local variable and a technique in a function. But their default value is not authorized.
EOF bug It increases while there is no input either from raw _input() an input operation.
Python Try-Except
Try

In python utilizing try, we can get the special case. In any case, If any code inside the attempt causes a special case, an exemption of the code will stop and hop to the aside from explanation. In any case, when a special case happens in the try block, Python searches for the coordinating aside from block to deal with it.

Syntax:

Try:

Statements

Except:

Statements

Statements

Example:

try:

x > 100

except:

print(“Something went wrong”)

print (“Even if it increased a bug, the program remains running”)

Output:

Something went wrong

Even if it increased a bug, the program remains running.

Another type of exception which we require to manage is the try-except structure:

Hence in the try structure, we may put the dubious program where the bug is likely. Then the try block, we can distinguish the except declaration. The block of code follows the except data. This handles the code as productively as could reasonably be expected.

Syntax

Try:

Statements

Except exceptions 1

——————–

———————

Except exceptions 2

…………

………….

else:

if there is no exception, this block is executed.

Example

try:

ab = open(“example”, “r”)

ab.write(“This is my test document for exception handling!!”)

except IOError:

print (“Bug: can\’t discover the document or read information”)

else:

print (“Written text in the document efficiently”)

Output

Error: can’t discover the document or read information

Features of try-except blocks:

An individual try block has various except declaration. This is valuable when the try block contains exemptions and throws various special cases.

Here we can give a generic except a condition which handles any exemption.

Afterwards the except statement, we can contain an else condition. If the program in the try structure doesn’t increase an exemption, the program in the else structure implements.

Can we use except class without exceptions?

Yes, we can utilize the except class where there is no particular case characterized. For the most part, the try get proclamation gets all the specific case that happens. Since in the correct programming exercise, try-except from isn’t supposed as a superior. Also, the try-except from proclamation gets all the exemptions.

How to raise an exception?

Utilizing the raise declaration, we can increase an exception in multiple methods.

Syntax

Raise [Exception [,args [,traceback]]]

The exception is a type of exception(for instance, NameError)

The argument is the argument type of value. This is an optional value.

The traceback object is used for an exception. This is also optional.

Example

try:

raise NameError(‘Hello’)

except NameError:

print(‘This is an instance of increasing an error’)

raise

Output

Traceback (most recent call last):

This is an instance of increasing an error

User-defined Exceptions

Python enables the use of generating and represent the exception of our own. Let us have a view on how to generate the user define exceptions.

Example

# define Python user-defined exceptions

Class Error (Exception):

“””Base class for other exceptions”””

Pass

Class minerror (Error):

“””Increased when the input value is too small”””

Pass

Class maxerror (Error):

“””Increased when the input value is too large”””

Pass

# Our main program

# User guesses a number until he/she gets it right

# you need to guess this number

number = 20

while True:

try:

i_num = int(input(“Enter a number: “))

if i_num < number:

raise minerror

elif i_num > number:

raise maxerror

break

except minerror:

print(“This value is less than the initialized number, try again!”)

print()

except maxerror:

Print(“This value is greater than the initialized number, try again!”)

Print ()

Print (“Congratulations! You guessed it correctly.”)

Output

Enter a number: 5

This value is less than the initialized number, try again!

Enter a number: 100

This value is higher than the initialized number, try again!

Enroll Yourself: Python Training

Copyright 1999- Ducat Creative, All rights reserved.