What Is Exception
What Is Exception
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.
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.
Example
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:
result = 10 / num
except ZeroDivisionError:
except ValueError as 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
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.
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]]]
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