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

What Is Exception

Uploaded by

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

What Is Exception

Uploaded by

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

What is Exception?

● 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.

Handling an exception
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 as elegantly as possible.

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.

Example code

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This example opens a file, writes content in the, file and comes out gracefully because there is no pr
Written content in the file successfully

This example tries to open a file where you do not have write permission, so it
raises an exception –
Error: can't find file or read data

Types
● 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.
In programming, an "exception" is an event that occurs during the execution of a
program that disrupts the normal flow of instructions. Exceptions are typically used to
handle error conditions or exceptional situations in a program.

When you "raise an exception," it means you deliberately create and trigger an
exception in your code to indicate that something unexpected or erroneous has
occurred. This is often done to gracefully handle errors or exceptional cases rather
than allowing the program to crash or produce unpredictable results.

Here's a brief overview of the concepts:

Exception: An exception is a Python object that represents an error or exceptional


condition. Exceptions can be of various types, such as ValueError, TypeError,
FileNotFoundError, or custom exception types created by developers. Each
type of exception is associated with a specific error condition.
Raising an Exception: To raise an exception in Python, you use the raise statement
followed by the exception type and an optional argument. The argument
provides additional information about the exception. For example:

Example

# Raise a ValueError exception with a custom error message

raise ValueError("This is a custom error message")

When this code is executed, it generates a ValueError exception and provides the
message "This is a custom error message" as additional information.
Handling Exceptions: To handle exceptions, you use try and except blocks. You
place the code that may raise an exception inside the try block, and in the
except block, you specify how to handle the exception. For example:

Example

try:

# Code that may raise an exception


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

result = 10 / num

except ZeroDivisionError:

print("Cannot divide by zero")

except ValueError as e:

print(f"Invalid input: {e}")

In this code, we use a try block to execute code that might raise exceptions. If an
exception occurs, the program jumps to the appropriate except block to handle
it. In this case, we have separate handlers for ZeroDivisionError and
ValueError.

By raising and handling exceptions in your code, you can gracefully deal with errors,
provide meaningful error messages, and prevent your program from crashing when
unexpected issues arise.
Argument of an Exception

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, Argument:
You can print value of Argument here...

If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are trapping
multiple exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause
of the exception. The variable can receive a single value or multiple values in
the form of a tuple. This tuple usually contains the error string, the error
number, and an error location.

Following is an example for a single exception –

# Define a function here.


def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");

This produces the following result


The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The
general syntax for the raise statement is as follows.

Syntax
raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (for example, NameError)


and argument is a value for the exception argument. The argument is
optional; if not supplied, the exception argument is None.

The final argument, traceback, is also optional (and rarely used in practice),
and if present, is the traceback object used for the exception.
Example

An exception can be a string, a class or an object. Most of the exceptions that the Python core raises

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

You might also like