Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Exception Handling in Python

Last Updated on September 22, 2023 by Mayank Dham

In this blog, we will learn exception handling in python. Let’s have a look at the content discussed below i.e. what we are learning in this article

What is Exception Handling in Python?

An occurrence that arises during the execution of a program and disrupts its normal flow is referred to as an exception. To safeguard your program from abrupt termination, Python generates exceptions during program execution. These exceptions in the Python programming language can either arise automatically due to errors or can be deliberately provoked and handled by the code you write.

The exception shows that even though the event might happen, it does so rarely. The caller function receives the exception when the method is unable to handle it. Eventually, the program ends abruptly when an exception is thrown outside of the main function.

Common Examples of Exception:

  • Division by Zero
  • Accessing a file that does not exist.
  • Addition of two incompatible types
  • Trying to access a nonexistent index of a sequence
  • Removing the table from the disconnected database server.
  • ATM withdrawal of more than the available amount

Why should you use Exceptions?

Here are the reasons for using exceptions in Python:

  • Exception handling in python allows you to separate error-handling code from normal code.
  • An exception is a Python object which represents an error.
  • As with code comments, exceptions help you to remind yourself of what the program expects.
  • It clarifies the code and enhances readability.
  • Allows you to stimulate consequences as the error-handling takes place in one place and in one manner.
  • An exception is a convenient method for handling error messages.
  • In Python, you can raise an exception in the program by using the raise exception method.
  • Raising an exception helps you to break the current code execution and returns the exception back to expection until it is handled.
  • Processing exceptions for components that can’t handle them directly.

Rules of Exceptions

Here are some essential rules of Python exception handling:

  • Exceptions must be class objects
  • For class exceptions, you can use a try statement with an except clause which mentions a particular class.
  • Even if a statement or expression is syntactically correct, it may display an error when an attempt is made to execute it.
  • Errors found during execution are called exceptions, and they are not unconditionally fatal.

Python Exception Handling Mechanism

Exception handling in python is managed by the following 3 keywords:

  • try
  • catch
  • finally
  • Throw or raise

Python Try Statement

A try statement consists of the keyword try, a colon (:), and a group of code that may contain exceptions. It contains a clause or clauses.
If no exceptions arise during the try statement’s execution, the interpreter ignores the try statement’s specified exception handlers.

A try suite expires if an exception occurs within it, and program control then passes to the matching except for the handler that came after the try suite.

Syntax:
try:
statement(s)

The catch Statement

The sort of exception that it is likely to catch is one that is taken one argument at a time by catch blocks. These justifications might be anything from a particular sort of exception that can be changed to a general category of exceptions.
Norms for the catch block:

  • You can define a catch block by using the keyword catch
  • The catch Exception parameter is always enclosed in parentheses
  • It always represents the type of exception that the catch block handles.
  • An exception handling code is written between two {} curly braces.
  • You can place multiple catch block within a single try block.
  • You can use a catch block only after the try block.
  • All the catch block should be ordered from subclass to superclass exception.

Example

try
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.printin("Caught first " + e.getMessage()); } catch (IOException e) {
System.err.printin("Caught second " + e.getMessage());
}

Finally Statement in Python

Whether or not there is an exception, the finally block always runs. You may write a block of code that comes after a try-catch block by using the final keyword.

A clause is optional, to sum up. It aims to provide cleanup procedures that must be followed in all circumstances.

try:
    raise KeyboardInterrupt
finally:
    print 'welcome, world!'

Output

Welcome, world!
KeyboardInterrupt

Finally, the clause is executed before the try statement.

Raise Statement in Python

The raise statement specifies an argument that initializes the exception object. Here, a comma follows the exception name, and argument or tuple of the argument that follows the comma.
Syntax:

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

In this syntax, the argument is optional, and at the time of execution, the exception argument value is always none.

Error Type Description
ArithmeticError ArithmeticError act as a base class for all arithmetic exceptions. It is raised for errors in arithmetic operations.
ImportError ImportError is raised when you are trying to import a module which does not present. This kind of exception occurs if you have made typing mistake in the module name or the module which is not present in the standard path.
IndexError An IndexErroris raised when you try to refer a sequence which is out of range.
KeyError When a specific key is not found in a dictionary, a KeyError exception is raised.
NameError A NameError is raised when a name is referred to in code which never exists in the local or global namespace.
ValueError Value error is raised when a function or built-in operation receives an argument that may be of the correct type but does not have a suitable value.
EOFerror This kind of error raises when one of the built-in functions (input() or raw_input()) reaches an EOF condition without reading any data.
ZeroDivisonError This type of error is raised when division or module by zero takes place for all numeric types.
IOError- This kind of error is raised when an input/output operation fails.
syntaxError SyntaxErrors are raised when there is an error in Python syntax.
IndentationError This error is raised when indentation is not properly defined

Conclusion:
This blog gives a brief explanation of exception handling in python in which we have discussed the definition, Rules, Examples of exception handling in python, we hope this article will help you to better understanding of the topic exception handling in python.

Frequently Asked Questions (FAQs) about Exception Handling in Python:

1.How does Python handle exceptions?
Python handles exceptions using the "try" and "except" blocks. The code that might cause an exception is placed within the "try" block, and potential exceptions are caught and managed in the corresponding "except" blocks.

2.What is the purpose of the "try" and "except" blocks?
The "try" block contains the code where an exception might occur. The "except" block, following the "try" block, holds the code to be executed when a specific exception occurs. It prevents the program from crashing and allows you to handle the error gracefully.

3.Can I have multiple "except" blocks for a single "try" block?
Yes, you can have multiple "except" blocks for a single "try" block. Each "except" block can handle a specific type of exception, allowing you to tailor your response based on the type of error that occurred.

4.What is the purpose of the "finally" block in exception handling?
The "finally" block is used to specify code that should be executed regardless of whether an exception was raised or not. It’s often used to release resources or perform cleanup tasks that should occur regardless of the outcome.

5.Can I raise my own exceptions in Python?
Yes, you can raise custom exceptions in Python using the "raise" statement. This allows you to create and trigger exceptions that are relevant to your program’s logic.

Leave a Reply

Your email address will not be published. Required fields are marked *