0% found this document useful (0 votes)
2 views

Exception Handling

An exception in Python is an event that disrupts the normal flow of a program, represented as a Python object. The document outlines built-in exceptions, how to handle exceptions using try-except blocks, and the creation of user-defined exceptions. It provides examples for handling exceptions and demonstrates how to capture exception arguments for additional context.

Uploaded by

shaikhmohd9870
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exception Handling

An exception in Python is an event that disrupts the normal flow of a program, represented as a Python object. The document outlines built-in exceptions, how to handle exceptions using try-except blocks, and the creation of user-defined exceptions. It provides examples for handling exceptions and demonstrates how to capture exception arguments for additional context.

Uploaded by

shaikhmohd9870
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Exceptions

▪ An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.
▪ In general, when a Python script encounters a situation that it cannot cope with, it raises an
exception.
▪ An exception is a Python object that represents an error.
▪ When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.

Built-in Exceptions:
▪ Here is a list of Standard Exceptions available in Python.
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to
any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a
numeric type.
FloatingPointError Raised when a floating-point calculation fails.
ZeroDivisonError Raised when division or modulo by zero takes place for all
numeric types
IndentationError Raised when indentation is not specified properly.
IOError Raised when an input/ output operation fails, such as the
open() function when trying to open a file that does not exist.
OSError Raised for operating system-related errors.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence.
NameError Raised when an identifier is not found in the local or global
namespace
Handling Exceptions :
▪ If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block.
▪ After the try: block, include an except: statement, followed by a block of code which handles the
problem .
▪ Syntax
try:
You do your operations here
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
else:
If there is no exception then execute this block.
▪ A single try statement can have multiple except statements.
▪ This is useful when the try block contains statements that may throw different types of
exceptions.
▪ You can also provide a generic except clause, which handles any exception.
▪ After the except clause(s), you can include an else-clause.
▪ The code in the else- block executes if the code in the try: block does not raise an exception.
▪ The else-block is a good place for code that does not need the try: block's protection.
▪ Example:
try:
f = open("testfile", "w")
f.write("This is my test file")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
f.close()
▪ Example: file doesn’t have write permission
try:
f = open("testfile", "r")
f.write("This is my test file ")
except IOError:
print ("Error: can\'t find file or read data")
else: print ("Written content in the file successfully")

Exception with Arguments :


▪ An exception can have an argument, which is a value that gives additional information about the
problem.
▪ The contents of the argument vary by exception.
▪ You capture an exception's argument by supplying a variable in the except clause as follows- try:
You do your operations here ...................... except ExceptionType as Argument: You
can print value of Argument here...
▪ Example:
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The argument does not contain
numbers\n",Argument)
temp_convert("xyz")

User-defined Exceptions :
▪ Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
▪ Here is an example related to RuntimeError.
▪ Here, a class is created that is subclassed from RuntimeError.
▪ This is useful when you need to display more specific information when an exception is caught.
▪ In the try block, the user-defined exception is raised and caught in the except block.
▪ Example:
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
try:
raise Networkerror("Bad hostname")
except Networkerror e:
print e.args

You might also like