Exception Handling in Python

Table of contents:

  1. What is an Exception?
  2. Exception versus Syntax error versus Logical error
  3. How to raise an Exception
  4. How to handle an exception : Try and Except block
  5. Using Finally

 

  1. What is an Exception?

Errors occur at the time of execution of a program are known as exception.

When an exception occurs it causes to stop the execution of program and pass to the calling process. If an exception is not handled on time it can cause your code to crash.

  1. Exception versus Syntax error versus Logical error?

Syntax error is when interpreter finds an incorrect statement. It simply means python doesn’t know how to execute that pattern:

e.g.

In above example, we found error syntax error because of more parenthesis.

Logical error is error when the mathematical logic or the reason behind an expression or statement is wrong. Because of this error we don’t get required result.

e.g.

If you want to get addition and use logic of subtraction, then it will be a logical error.

Runtime error are exceptions. They occurs in some specific cases.

  1. How to raise an exception?

In some specific cases we can raise an exception by our self. It will stop the current execution of code and return the exception.

Syntax to raise an exception:

We can also raise an exception by assigning variable or by defining a function.

Using a variable

By defining a function

4. How to handle an exception : Try and Except block

It is necessary to handle an exception as soon as we see it, else it can crash the program.

For this we use try and catch block.

In try block we put the code that causes the exception while in except block we give the response to any exception.

To handle this TypeError exception we will use try and except block:

This time output will be:

5. Using Finally

As above, we saw when an exception occurs how we can handle it using try and catch block.

In some cases we want some code to run at any condition (Doesn’t matter if exception occurs or not).

To understand the concept of finally, let’s see this example:

In above code we took an string and used try then except to handle the exception at last we used finally block. The code in finally will always get executed.

Output:

As we can see, code in finally where string contains the value “abc” get converted into “abc will change into python”.

About

Codec Networks provides IT Trainings from EC Council CEH ECSA, LPT, CHFI, Network Security, Penetration Testing, ISACA, ISC2, PECB ISO 27001LA LI, Cisco Networking CCNA CCNP, Linux Administration RHCE, Prog Languages JAVA, Advanced Java, android development. We also offer B2B Industry Solutions and Services in IT | Information|Cyber Security in Delhi NCR India.

View all posts by

Leave a Reply

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