×

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program.

Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding mistakes like syntax errors (punctuation or grammar flaws), rather it will suddenly stop.

A sudden exit is awful for both the developer and end client.

Rather than an emergency stop, you can utilize a try-except to appropriately manage the issue. A sudden end will occur on the off chance that you don't as expect handle exceptions.

What is Try block?

  1. Try block is used to test codes for errors or we can say exceptions are handled using “try block”.
  2. Try block contains the code which the user thinks might raise an exception. If the code inside the try clause executes that simply means that the code doesn’t contain any error or exceptions.
  3. We cannot have a try block without except block.

Let us take a real-life example,

# working of try()

def divide(x, y):

               try:

                               result = x // y

                               print("Yeah ! Your answer is :", result)

               except ZeroDivisionError:

                               print("Sorry ! You are dividing by zero ")

divide(3, 2)

Output:

('Yeah ! Your answer is :', 1)

What is Except block?

  1. It is common in the python world to use exceptions for flow control.
  2. This statement runs when an error is encountered in a given code.
  3. The use of these statements is completely optional and isn’t strictly necessary.
  4. Except block is used to catch errors in a program.
  5. Except block catches the errors in the code written in the try block.

Let’s take a real-life example,

def divide(x, y):

               try:       

                               result = x // y

                               print("Your answer is :", result)

               except ZeroDivisionError:

                               print("You are dividing by zero ")

divide(3, 0)

Output:

Sorry ! You are dividing by zero

It returned an error in the except block cause we tried to divide the value by 0.

Note: Only except clause will run because there is an exception.

Most common exception in python:

AttributeError

This exception addresses the activity of referring to or appointing to an attribute that doesn't in any case exist - the exemplary invalid reference. Certain parameters are relied upon to have a value in the happy case will as often as possible, not at runtime, which causes this exception.

TypeError:

TypeError is an extremely normal exception and gets tossed when an individual operation is performed on a different type. On the off chance that this happens in a web context because of distorted client input (particularly basic in a REST API), the exception gets covered inside a log file. Utilizing an instrument like Raygun will guarantee you are notified and have every one of the information you want to investigate the exception and push a fix rapidly.

ValueError

ValueError occurs when a user passes an invalid value but a correct type of argument to the function.

AssertionError

It’s a programming concept that a user applies while writing a code where he declares a condition to be true where he uses an assert statement before running the module.

If it returns True then it moves to the next line but if it returns False the program stops and returns AssertionError.

Conclusion

In this article, we tried to learn about try block and except block and which are the most common exceptions you can come across in python. Using Try and except block isn’t strictly necessary and completely optional but is a great way to catch exceptions in our codes and programs.


Related Topics

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python String count() method

Python String count() method The string.count() method returns the number of times a specified value appears in the string. Syntax string.count(sub[, start[, end]]) Parameter sub: This parameter represents a substring to be searched. start: This parameter...

1 minute read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.