×

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

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

StandardScaler in Sklearn

When and How Should You Use StandardScaler? StandardScaler comes into play whenever the properties of the provided dataset change significantly within their ranges or are recorded in different measurement units. Since using...

4 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.