KEMBAR78
Exception Handling | PDF | Computer Program | Programming
0% found this document useful (0 votes)
6 views8 pages

Exception Handling

The document provides an overview of exception handling in Python, explaining how to manage errors that occur during code execution to prevent program crashes. It categorizes errors into syntax errors and logical errors (exceptions), detailing how to use try, except, else, and finally blocks to handle these exceptions effectively. Additionally, it discusses raising exceptions and creating user-defined exceptions for better error management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Exception Handling

The document provides an overview of exception handling in Python, explaining how to manage errors that occur during code execution to prevent program crashes. It categorizes errors into syntax errors and logical errors (exceptions), detailing how to use try, except, else, and finally blocks to handle these exceptions effectively. Additionally, it discusses raising exceptions and creating user-defined exceptions for better error management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

EXCEPTION HANDLING

Exception Handling
Introduction

In Python, different errors may occur while executing a code due to incorrect input or even other
unpredictable errors. Where the program encounters an error and something goes wrong with the
program, the Python interpreter interrupts the current process and moves it over to the calling process –
before it handles.

It is Python’s default exception-handling behavior. If not handled, the program crashes automatically
and prints an error code. You must handle the exceptions in your program if you do not want this
default action. And that’s where blocks come in.
Exception handling in Python is a technique of processing problems that occur during the execution of
the program. Using exception handling, we can test the code and avoid it from exiting abruptly.

Python Errors
You may make certain mistakes when developing a program that leads to errors while trying to execute
it. During its execution, Python program stop working as soon as it encounters an error, that is not
handled. These errors categorize into two categories: syntax errors and logical errors – often called
Exceptions.
Python Syntax Errors
Syntax errors or parsing errors are triggered by not observing the correct structure of the program. The
most basic form of error is a Syntax error. They occur when the Python parser cannot interpret a code
line. Many syntax errors are typos, incomplete or incorrect arguments. If you get this error, try to look
at the code for one of these keywords: misspelling, incomplete, or misusing. for action in ["alpha ",
"beta", "gamma"]

SyntaxError : invalid syntax

UBDTCE , DAVANGERE PAGE 1


EXCEPTION HANDLING

Python Logical Errors (Exceptions)


After passing the syntax check, errors that occur during runtime are called logical or exceptions
. It is the most challenging type of error since it gives unexpected results and can crash
errors the program. Many different things will arise if Logical error encounters. Whenever such
errors occur,

Python generates an Exception object. Exceptions occur where the python parser understands what to
do with this piece of code but cannot do it. Example: attempting to reach the Internet without an internet
connection: the Python interpreter knows but cannot execute the instruction.
Illegal operations will also raise Exceptions. Python includes several built-in exceptions when the
following errors occur: ValueError, TypeError, ZeroDivisionError, ImportError – and so
on. Consequently, Python prints the Traceback of the error if not correctly handled. And in the last line
of the message, what sort of exception in the program has encountered, along with specifics of what
error caused. for i in [10, 20, 30]:

print(i / 0)

Traceback (most recent call last):

File "<stdin>", line 2, in <module>

ZeroDivisionError: division by zero

Fortunately, these exceptions may catch and handle, and then the program adapted such that it does not
crash. In Python, you can even define your exceptions if needed! After looking at the variations between
syntax errors and exceptions, go ahead and see how to raise, catch, and handle these exceptions in
Python.
Python Assertion

Instead of waiting for a program to crash, you may also begin by creating an assertion in Python and
check if a specified requirement has been fulfilled. If this is true, so that is excellent – the program
carries ahead. But if the situation proves false, the program can throw an
AssertionError exception from .
Let’s have a look at the illustration below where the asserted the code on a Linux system:

UBDTCE , DAVANGERE PAGE 2


EXCEPTION HANDLING

import sys
1 assert ('linux' in sys.platform), "This code runs on

2 Linux only."

If you run this code on a Linux machine, the assertion goes through. The outcome of the assertion
would be false if you were to run this code on a Windows machine or somewhere else, and the result
would be as follows:
1 Traceback (most recent call last):

2 File "<input>", line 2, in <module>

3 AssertionError: This code runs on Linux only.

The last thing the program does is throw an AssertionError exception. The program stops and does
not proceed. Still, What if you don’t like that?! Then you’re going to have to catch this exemption.
Python Try … Except

When there is an error: Python will typically throw an exception, create an error message, and interrupt
the program if this exception is not correctly handled. When it arises, and within the try block, the try
block’s remainder ignore when this error is found, and the exceptional block is executed.
Catch ALL Exceptions
When an error occurs: Python would normally throw an exception, generate an error message, and stop
the program if this exception is not handled correctly. When this error occurs during its execution – and
inside the try statement – the rest of the try block is skipped as soon as this error is encountered, and the
except block is executed.
1 try:

2 statement_1

3 statement_fail

4 statement_not_executed 5 except:

UBDTCE , DAVANGERE PAGE 3


EXCEPTION HANDLING

6 print('Something went wrong!')

The try and except block in Python used to catch and handle all exceptions. Python will execute the
code following the try block until an exception encounter. The code that follows the except block
determines how your program responds to exceptions. Consequently, the except block use to catch and
handle the exceptions encountered in the try block.
1 try:

2 statement_1

3 statement_fail

4 statement_not_executed

5 except Exception as error:

6 print('Something went wrong:', error)

So, if you don’t want to run the same code block with every exception? Fortunately, Python provides
you with the ability to catch one or more exceptions at a time. Let’s explore
Catch Single Exception
We did not mention a particular exception in the previous example except block. It is not a good
programming technique, so it catches all exceptions irrespective of your error and handles all exceptions
in the same manner. Nevertheless, you should define the exceptions from a clause other than that:
ValueError , TypeError , ZeroDivisionError , ImportError , etc.
1 try:

2 x = 1/0

3 statement_not_executed

4 except ZeroDivisionError:

5 print('Something went wrong!')

In the case above, the try block creates an exception since it divides a number by zero. Therefore the
ZeroDivisionError except block is only performed for this particular error – in this situation, no other
errors can handle, and your program can crash.
That’s fine, but you wonder: how can you handle in Python with several exceptions? This is the answer

UBDTCE , DAVANGERE PAGE 4


EXCEPTION HANDLING

Catch Multiple Exceptions


A try clause can have any number of except block to handle different exceptions. However, only one
will be executed in case an exception occurs. Consequently, you should describe as many except blocks
as you want – so that you can independently and differently catch and handle unique exceptions.

1 try:

2 x = 1/0

3 except ZeroDivisionError: 4 print('Attempt to divide by zero') 5 except:

6 print('Something else went wrong')

And if you choose to run the same block of code for many exceptions, specify ALL exceptions inside a
tuple :
1 try:

2 x = 1/0

3 except TypeError:

4 print('TypeError is raised')

5 except (ZeroDivisionError, ValueError):

6 print('ZeroDivisionError or ValueError is raised')

7 except:

8 print('Something else went wrong')

Python handles exceptions not only when they occur try block in the , If an error arises, and you
don’t know how to handle it correctly, then "pass" keyword should be used to avoid a crash of
your program.
1 def division_by_zero():

2 x = 1/0

3 try:

4 division_by_zero()

5 except Exception as e:

6 print('Attempt to divide by zero')

UBDTCE , DAVANGERE PAGE 5


EXCEPTION HANDLING

7 pass

8 next_statement_executed

Your program won’t crash any more because all exceptions raised during its execution can be caught
and handled! How can you execute a code block only if there were no exceptions to the try clause?
Python Else Clause

In
certain cases, you would want to run a certain code within the try clause that was error-free. In such
instances, the optional else keyword with the try statement may be used to define a code block to be
executed if and only no errors have been raised.
1 try: 2 x

= 1/1

3 except:

4 print('Something went wrong') 5 else:

6 print('Nothing went wrong')

Here’s an example that divides the integer 1 by 1 and saves the result in variable x. If an error occurs
during this phase, an exception is raised. This error will be caught and handled by the except clause –
output 'Something went wrong.' else, it will output 'Nothing went wrong' so there are no exceptions to
this program and the else clause was applied.

UBDTCE , DAVANGERE PAGE 6


EXCEPTION HANDLING

Python Finally Clause

The try..except statement in Python has another and optional finally clause. If specified, the finally
block will always be executed – regardless of whether the try block raises an error or not, and un der
any circumstances.
1 try:

2 x = 1/0 3

except:

4 print('Something went wrong') 5

finally:

6 print('Always execute this')

Imagine you would still take steps to clean up after the code is executed. Python helps you to do so by
utilizing the finally clause.
1 f = open('file.txt') 2

try:

3 print(f.read()) 4

except:

5 print("Something went wrong")

UBDTCE , DAVANGERE PAGE 7


EXCEPTION HANDLING

Raising an Exception

In Python programming, exceptions are raised runtime. But, as a Python developer, you
manually throw an exception at any time. To raise such an exception, "raise" use the reserved keyword.
A customized exemption may follow this statement. Optionally you should specify what type of error to
arise and pass the exception values to explain that the exception has been raised. And the machine pauses
and shows the exception to the panel – providing clues to what went wrong and debugged.
1 # Raise built-in exception 'NameError' 2

raise NameError('An exception occured!') 3

# Output:

4 # Traceback (most recent call last):

5 # File "<stdin>", line 1, in <module>

6 # NameError: An exception occured!

User-defined Exceptions
Users may define customized exceptions in Python by creating a new class. This exception class must
be obtained from the built-in Exception class, explicitly or implicitly. Some of the exceptions included
are also drawn from this class.
Here, we have created a user-defined CustomError exception, which inherits from the exception class.
Like any other exceptions, this new exception can be raised using the raise statement – and with an
optional error message. class CustomError(Exception):

pass raise CustomError raise CustomError("A

custom error occurred") # Traceback (most

recent call last):

# File "<stdin>", line 4, in <module>

# CustomError: A custom error occurred

UBDTCE , DAVANGERE PAGE 8

You might also like