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

Exception Handling

Exception handling in Python allows code to gracefully handle errors and unexpected conditions. There are built-in exceptions for common errors like division by zero. Code that may cause an exception is placed in a try block, and except blocks define what code runs if a particular exception occurs. Finally blocks contain cleanup code that always runs whether an exception occurred or not. User-defined exceptions can also be raised to handle custom error conditions.

Uploaded by

Raviraj kundekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views

Exception Handling

Exception handling in Python allows code to gracefully handle errors and unexpected conditions. There are built-in exceptions for common errors like division by zero. Code that may cause an exception is placed in a try block, and except blocks define what code runs if a particular exception occurs. Finally blocks contain cleanup code that always runs whether an exception occurred or not. User-defined exceptions can also be raised to handle custom error conditions.

Uploaded by

Raviraj kundekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Exception Handling

Exception Handling
• Run time errors are known as Exception.
• Whenever an exception occurs the program
halts the execution and thus further code is
not executed.
• Exception in python code can also be handled
using try-except block.
Built-in Exception
• Python has many built-in exceptions which
forces your program to output an error when
something in goes wrong.
Built-in Exception
Python has many built-in exceptions which forces your
program to output an error when something in goes wrong.

EXCEPTION NAME DESCRIPTION


Exception Base class for all exceptions
Base class for all built-in exceptions except StopIteration and
StandardError
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
Raised when a calculation exceeds maximum limit for a numeric
OverflowError
type.
FloatingPointError Raised when a floating point calculation fails.
Raised when division or modulo by zero takes place for all
ZeroDivisionError
numeric types.
Raised when there is no input from either the raw_input() or
EOFError
input() function and the end of file is reached.
Built-in Exception
ImportError Raised when an import statement fails.
Raised when the user interrupts program execution, usually by
KeyboardInterrupt
pressing Ctrl+c.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
Raised when an identifier is not found in the local or global
NameError
namespace.
Raised when trying to access a local variable in a function or method
UnboundLocalError
but no value has been assigned to it.
Raised when an input/ output operation fails, such as the print
IOError statement or the open() function when trying to open a file that
does not exist.
OSError Raised for operating system-related errors.

SyntaxError Raised when there is an error in Python syntax.

IndentationError Raised when indentation is not specified properly


Built-in Exception
Raised when the interpreter finds an internal problem,
SystemError but when this error is encountered the Python
interpreter does not exit.
Raised when Python interpreter is quit by using the
SystemExit sys.exit() function. If not handled in the code, causes the
interpreter to exit.
Raised when an operation or function is attempted that is
TypeError
invalid for the specified data type.
Raised when the built-in function for a data type has the
ValueError valid type of arguments, but the arguments have invalid
values specified.
Handling Exception
Exception Handling:
• The suspicious code can be handled by using
the try block.
• Enclose the code which raises an exception
inside the try block.
• The try block is followed except statement.
• It is then further followed by statements
which are executed during exception and in
case if exception does not occur.
try:
malicious code
except Exception1:
execute code try:
a=10/0
except Exception2: print a
execute code except ArithmeticError:
print "This statement is raising an exception"
.... else:
.... print "Welcome"
>>>
except ExceptionN: This statement is raising an exception
execute code
else:
In case of no exception,
execute the else block code.
Exception with no exception
Except statement can also be used without specifying Exception.

try:
code
except:
code to be executed in case exception occurs.
else:
code to be executed in case exception does not occur.

try:
a=10/0;
except:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
>>>
Arithmetic Exception
Declaring Multiple Exception
Multiple Exceptions can be declared using the same except statement:
Syntax:
try:
code
except Exception1,Exception2,Exception3,..,ExceptionN
execute this code in case any Exception of these occur.
else:
execute code in case no exception occurred.
try:
n=int(input("enter nume"))
d=int(input("enter denom"))
div=n/d
print(div)
except (ValueError,ZeroDivisionError):
print("Value Error/Zero Division Error")

enter nume3
enter denomsam
Value Error/Zero Division Error
>>>
Finally Block:
•In case if there is any code which the user want to be
executed, whether exception occurs or not then that
code can be placed inside the finally block.
•Finally block will always be executed irrespective of
the exception.
Syntax:

try:
Code
except:
execute this code in case any Exception of these occur.
finally:
code which is must to be executed
try:
n=int(input("enter nume:"))
d=int(input("enter denom:"))
div=n/d
print(div)
except (ValueError,ZeroDivisionError):
print("Value Error/Zero Division Error")
finally:
print("Done")

enter nume:4
enter denom:2
2.0
Done
>>> ================================ RESTART
================================
>>>
enter nume:sam
Value Error/Zero Division Error
Done
>>>
Raise an Exception
Raise an Exception:
• You can explicitly throw an exception in Python using
raise statement.
• raise will cause an exception to occur and thus
execution control will stop in case it is not handled.
Syntax:
• raise [Exception,[args,[traceback]]]
>>> raise valueError
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise valueError
NameError: name 'valueError' is not defined
Exception with arguments
try:
statements
except ExceptionType as argument:
execute this code in case any Exception of these occur.

try:
a=int(input("enter a num:"))
b=int(input("enter a num:"))
d=a/b
print(d)
except Exception as e:
print (type(e))
>>>
enter a num:3
enter a num:0
<class 'ZeroDivisionError'>
User Defined Exception
• Some time while writing code the built in
exception types are not serving the purpose
for handling an execution.
• To handle this problem in python programmer
can write and handle their own exception.

You might also like