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

Exception Handling

Exception handling in Python is a mechanism to catch and manage errors that occur during program execution, categorized into compile-time and run-time errors. It enhances code readability and robustness by separating error-handling code from normal code, allowing for clearer and fault-tolerant programs. The process involves using try and except blocks to manage exceptions, with options for handling multiple errors and ensuring certain code runs regardless of exceptions through the finally block.

Uploaded by

robikan2022
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)
4 views

Exception Handling

Exception handling in Python is a mechanism to catch and manage errors that occur during program execution, categorized into compile-time and run-time errors. It enhances code readability and robustness by separating error-handling code from normal code, allowing for clearer and fault-tolerant programs. The process involves using try and except blocks to manage exceptions, with options for handling multiple errors and ensuring certain code runs regardless of exceptions through the finally block.

Uploaded by

robikan2022
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/ 4

Exception Handling

When we create and develop programs, errors occur naturally. Sometimes, we misspell a name or keyword, or sometimes
we unknowingly change the symbols. These are very common and easy to handle errors. But programming is not that easy
and errors are not that simple. So, to handle virtually any type of errors that may occur, language developers have created
numerous ways to catch and prevent them. Python also supports a specific and well-defined mechanism of catching and
preventing errors of any type that may occur. This mechanism is known as Exception Handling.

Broadly there are two types of errors :

(i) Compile-time errors. These are the errors resulting out of violation of programming language’s grammar rules e.g.,
writing syntactically incorrect statement like : print ("A" + 2) will result into compile-type error because of invalid syntax.
All syntax errors are reported during compilation.

(ii) Run-time errors. The errors that occur during runtime because of unexpected situations. Such errors are handled
through exception handling routines of Python. Exception handling is a transparent and nice way to handle program
errors.

Advantages of exception handling

(i) Exception handling separates error-handling code from normal code.


(ii) It clarifies the code (by removing error-handling code from main line of program) and enhances readability.
(iii) It stimulates consequences as the error-handling takes place at one place and in one manner.
(iv) It makes for clear, robust, fault-tolerant programs.
So, we can summarize Exception as : It is an exceptional event that occurs during runtime and causes normal
program flow to be disrupted.

Some common examples of Exceptions are :

 Divide by zero errors


 Accessing the elements of an array beyond its range
 Invalid input
 Hard disk crash
 Opening a non-existent file etc.

For instance, consider the following code :

>>> print (3/0)

If we execute above code, we’ll receive an error message as :


Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print 3/0
ZeroDivisionError: integer division or modulo by zero

Concept of Exception Handling


The global concept of error-handling is pretty simple. That is, write your code in such a way that it raises some error flag
every time something goes wrong. Then trap this error flag and if this is spotted, call the error handling routine.

The raising of imaginary error flag is called throwing or raising an error. When an error is thrown, the overall system
responds by catching the error. And surrounding a block of error-sensitive-code-with-exception-handling is called trying
to execute a block.
Exception Handling in Python
Exception Handling in Python involves the use of try and except clauses in the following format wherein the code that
may generate an exception is written in the try block and the code for handling exception when the exception is raised, is
written in except block.
See below :
try :
#write here the code that may generate an exception
except :
#write code here about what to do when the exception has occurred
For instance, consider the following code:

We see, now the output produced does not show the scary red-coloured standard error message ; it is now showing what
you defined under the exception block.
Consider another code that handles an exception raised when a code tries conversion from text to a number :
try:
x = int("XII")
except:
print ("Error converting'XII'to a number")

The output generated from above code is not the usual error now, it is:
Error converting ‘XII’ to a number
General Built-in Python Exceptions
The built-in exceptions can be generated by the interpreter or built-in functions. Some common built-in exceptions in
Python are being listed below:
Second Argument of the except Block
We can also provide a second argument for the except block, which gives a reference to the exception object. We can do it
in following format:
try:
# code
except <ExceptionName> as <exArgument> :
# handle error here
The except clause can then use this additional argument to print the associated error-message of this exception as : str
(exArgument). Following code illustrates it :

Handling Multiple Errors


Multiple types of errors may be captured and processed differently. It can be useful to provide a more exact error message
to the user than a simple “an error has occurred.” In order to capture and process different type of exceptions, there must
be multiple exception blocks – each one pertaining to different type of exception.

The last else : clause will execute if there is no exception raised, so you may put your code that you want to execute when
no exceptions get raised.
The finally Block
We can also use a finally: block along with a try: block, just like you use except: block, e.g., as : try:
# statements that may raise exception
[except:
# handle exception here]
finally:
# statements that will always run
The difference between an except: block and the finally: block is that the finally: block is a place that contains any code
that must execute, whether the try: block raised an exception or not.
For example,

You may combine finally: with except: clause. In such a combination, the except: block will get executed only in case an
exception is raised and finally: block will get executed ALWAYS, in the end. Following code illustrates it:

because finally : block gets executed always in the end.

You might also like