Network and Network Types5

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

Exception

Handling
Error in Python can be of two types i.e. Syntax errors
and Exceptions. Errors are problems in a program due
to which will stop the program from execution. On the
other hand, exceptions are raised when some internal
events occur due to limitation of hardware or software
part, which change the normal flow of the program.
Some terminology used within exception handling follows.
Description Python Terminology
An unexpected error that occurs during runtime - Exception
A set of code that might have an exception thrown in it. - try block
The process by which an exception is generated and passed
to the program. - Throwing or raising an error
Capturing an exception that has just occurred and executing
statements that try to resolve the problem - Catching
The block of code that attempts to deal with the exception
(i.e., problem).
except clause or except/exception
block or catch block
The sequence of method calls that brought control to the
point where the exception occurred. - Stack trace
When to Use Exception Handling
The exception handling is ideal for :
m processing exceptional situations.
m processing exceptions for components that cannot
handle
them directly.
m large projects that require uniform error-processing.
Different types of exceptions in
python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in
the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object
of the wrong type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in
the current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or
other sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does
not represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an
object, such as trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number
by zero.
• ImportError: This exception is raised when an import statement fails to find or load a
module.
Differencebetween Syntax Error
and Exceptions
Syntax Error: This error is caused by the wrong syntax in the
code.
if(amount > 999)
print(“amount more than 1000")
if(amount > 999)

Exceptions: Exceptions are raised when the program is


syntactically
correct, but the code results in an error. This error does not stop the
execution of the program, however, it changes the normal fl ow of the
program.
a = 10 / 0
print(a)
handling exceptions using finally blocks
try-except-
•try:
• # Some Code....which may have runtime error
•except:
• # optional block
• # Handling of exception (if required)

•else:
• # execute if no exception
•finally:
• # Some code .....(always executed)
Handling Errors
try:
# code
except <ExceptionName> as
<exArgument> :
# handle error here
try:
print ("result of 10/5 = ", (10/5))
print ("result of 10/0 = ", (10/0))
except ZeroDivisionError as e :
print ("Exception - ", str(e))
Handling Multiple Errors

This is done as per following format :


try:
# :
except <exceptionName1> :
# :
except <exceptionName2> :
# :
except :
# :
else :
#If there is no exception then the
statements in this block get executed.
try:
k = 9//0 # raises divide by zero
exception. print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Raising/Forcing an Exception
In Python, you can use the raise keyword to raise/force an exception. That means, you as
programmer can force an exception to occur through raise keyword. It can also pass a
custom
message to your exception handling module. For example :
raise <exception> (<message>)
The exception raised in this way should be a pre-defined Built-in exception. Consider
following
code snippet that forces a ZeroDivisionError exception to occur without actually dividing a
value by zero :
try :
a = int(input("Enter numerator :"))
b = int(input("Enter denominator :"))
if b == 0 :
raise ZeroDivisionError(str(a) + "/0 not possible")
print (a/b)
except ZeroDivisionError as e :
print ("Exception", str(e))
Advantages of Exception
Handling:
• Improved program reliability
• Simplified error handling
• Cleaner code
• Easier debugging

Disadvantages of Exception Handling:


• Performance overhead
• Increased code complexity
• Possible security risks

You might also like