×

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

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Periodogram in Python

Python:  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 is said...

3 minutes read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Standard GUI Unit Converter using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

12 minutes read.

How to Substring a String in Python

String Unicode characters collection is referred to as a String. It consists of a succession of characters, including alphanumeric and special characters. Substring: Core Concept A substring is a piece of a string....

5 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

How to Import Files in 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.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.