0% found this document useful (0 votes)
9 views10 pages

What Is An Exception

An exception is an error that occurs during program execution, which can be handled to prevent crashes. Python allows raising exceptions using the 'raise' statement and provides a structured way to handle them using 'try' and 'except' blocks. Custom exceptions can also be created by extending the BaseException class, allowing for more specific error handling in programs.

Uploaded by

Fawaz Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

What Is An Exception

An exception is an error that occurs during program execution, which can be handled to prevent crashes. Python allows raising exceptions using the 'raise' statement and provides a structured way to handle them using 'try' and 'except' blocks. Custom exceptions can also be created by extending the BaseException class, allowing for more specific error handling in programs.

Uploaded by

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

What is an Exception?

An exception is an error that happens during execution of a program. When that


error occurs, Python generate an exception that can be handled, which avoids
your program to crash.

Why use Exceptions?


Exceptions are convenient in many ways for handling errors and special
conditions in a program. When you think that you have a code which can
produce an error then you can use exception handling.

Raising an Exception
You can raise an exception in your own program by using the raise exception
statement.

Raising an exception breaks current code execution and returns the exception
back until it is handled.

Exception Errors
Below is some common exceptions errors in Python:
IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrup
key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data.

Exception Errors Examples:


Now, when we know what some of the exception errors means, let's see some
examples:
except IOError:
print('An error occurred trying to read the file.')

except ValueError:
print('Non-numeric data found in the file.')

except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')

except KeyboardInterrupt:
print('You cancelled the operation.')

except:
print('An error occurred.')

Exception handling enables you handle errors gracefully and do something meaningful about it.
Like display a message to user if intended file not found. Python handles exception
using try .. except .. block.

Syntax:
try:

# write some code

# that might throw exception

except <ExceptionType>:

# Exception handler, alert the user

As you can see in the try block you need to write code that might throw an exception. When an
exception occurs code in the try block is skipped. If there exist a matching exception type
in except clause then it’s handler is executed.

Let’s take an example:

try:
f = open('somefile.txt', 'r')
print(f.read())
f.close()
except IOError:
print('file not found')

Note: The above code is only capable of handling IOError exception. To handle other kind of
exception you need to add more except clause.
A try statement can have more than once except clause, It can also have optional else
and/or finally statement.

try:
<body>
except <ExceptionType1>:
<handler1>
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
=======================================================
====================

try:

num1, num2 = eval(input("Enter two numbers, separated by a comma : "))

result = num1 / num2

print("Result is", result)

except ZeroDivisionError:

print("Division by zero is error !!")

except SyntaxError:

print("Comma is missing. Enter numbers separated by comma like this 1, 2")

except:

print("Wrong input")

else:

print("No exceptions")

finally:

print("This will execute no matter what")


Raising exceptions
To raise your exceptions from your own methods you need to use raise keyword like this.

raise ExceptionClass("Your argument")

Let’s take an example:

def enterage(age):

if age < 0:

raise ValueError("Only positive integers are allowed")

if age % 2 == 0:

print("age is even")

else:

print("age is odd")

try:

num = int(input("Enter your age: "))

enterage(num)

except ValueError:

print("Only positive integers are allowed")

except:

print("something is wrong")
Using Exception objects:-
Now you know how to handle exception, in this section we will learn how to access exception
object in exception handler code. You can use the following code to assign exception object to a
variable.

try:

# this code is expected to throw exception

except ExceptionType as ex:

# code to handle exception

try:

number = eval(input("Enter a number: "))

print("The number entered is", number)

except NameError as ex:

print("Exception:", ex)

Creating custom exception class


You can create a custom exception class by Extending BaseException class or subclass
of BaseException .
Create a new file called NegativeAgeException.py and write the following code:-

class NegativeAgeException(RuntimeError):

def __init__(self, age): #special member assign value to variable.

super().__init__() #base class contain accessing in current class

self.age = age

Using custom exception class:-


def enterage(age):
if age < 0:
raise NegativeAgeException("Only positive integers are allowed")

if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except NegativeAgeException:
print("Only positive integers are allowed")
except:
print("something is wrong")

This program will ask the user to enter a number until they guess a stored number correctly.

To help them figure it out, a hint is provided whether their guess is greater than or less than the
stored number.
# define Python user-defined exceptions:

class Error(Exception):

"""Base class for other exceptions"""

pass

class ValueTooSmallError(Error):

"""Raised when the input value is too small"""

pass

class ValueTooLargeError(Error):

"""Raised 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 = 10

while True:

try:

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

if i_num < number:

raise ValueTooSmallError

elif i_num > number:

raise ValueTooLargeError
break

except ValueTooSmallError:

print("This value is too small, try again!")

print()

except ValueTooLargeError:

print("This value is too large, try again!")

print()

print("Congratulations! You guessed it correctly.")

A critical operation which can raise exception is placed inside the try clause and the
code that handles exception is written in except clause.

It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.

# import module system to get the type of exception:-

import sys

randomList = ['a', 0, 2]

for entry in randomList:

try:

print("The entry is", entry)

r = 1/int(entry)

break

except:
print("Oops!",sys.exc_info()[0],"occured.")

print("Next entry.")

print()

print("The reciprocal of",entry,"is",r)

>>> raise KeyboardInterrupt

Traceback (most recent call last):

...

KeyboardInterrupt

>>> raise MemoryError("This is an argument")

Traceback (most recent call last):

...

MemoryError: This is an argument

>>> try:

... a = int(input("Enter a positive integer: "))

... if a <= 0:

... raise ValueError("That is not a positive number!")

... except ValueError as ve:

... print(ve)

...

Enter a positive integer: -2

That is not a positive number!

You might also like