Python do nothing on exception

Python do nothing on exception

Last updated: Feb 20, 2023
Reading time · 2 min

banner

# Using try without except (ignoring exceptions) in Python

Use the pass statement to use a try block without except. The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

Copied!
my_list = [] # ✅ Ignore any exception try: print(my_list[100]) except: # 👇️ this runs pass

using try without except

We used a pass statement to ignore an exception.

The code in the try block could raise any exception and it would get passed to the except block.

Copied!
my_list = [] # ✅ Ignore any exception try: # 👇️ raises ValueError my_list.remove(1000) except: # 👇️ this runs pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

In general, using an except statement without explicitly specifying the exception type is considered a bad practice.

# Ignoring only specific errors

An alternative approach is to scope the except block to a specific error.

Copied!
my_list = [] try: print(my_list[100]) except IndexError: # 👇️ this runs pass

ignoring only specific errors

The except block only handles IndexError exceptions.

If an exception of any other type is raised, the except block won’t handle it.

For example, the following code raises a ZeroDivisionError in the try block and crashes the program.

Copied!
# ⛔️ ZeroDivisionError: division by zero try: print(25 / 0) except IndexError: pass

# Ignoring multiple, specific errors

You can also specify multiple exception classes in an except block.

Copied!
my_list = [] try: print(25 / 0) except (IndexError, ZeroDivisionError): # 👇️ this runs pass

ignoring multiple specific errors

If you have to specify multiple exception classes, make sure to wrap them in parentheses.

You can view all of the exception classes in Python in the Exception hierarchy list in the docs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Игнорирование исключений в Python: как это сделать?

Иногда в процессе написания кода на Python сталкиваются с ситуацией, когда в блоке try. except возникает исключение, которое не является критическим и не мешает дальнейшей работе программы. В таком случае, возникает потребность «проигнорировать» это исключение и продолжить выполнение кода. Однако, если оставить блок except: пустым или заполнить его комментарием #do nothing , Python вернет синтаксическую ошибку.

Вот пример ситуации, когда такое может произойти:

try: some_code_that_might_raise_an_exception() except: # Ничего не делать и продолжить

Итак, как же можно «игнорировать» исключение и продолжить выполнение кода? Для этого существует несколько подходов.

Использование оператора pass

Одним из способов является использование оператора pass в блоке except: . pass в Python — это оператор-заполнитель, который не делает абсолютно ничего. Он используется там, где синтаксически требуется какое-то выражение, но программно ничего делать не требуется.

try: some_code_that_might_raise_exception() except: pass

В этом случае, если код в блоке try: вызовет исключение, Python выполнит блок except: и продолжит выполнение программы дальше.

Использование continue в цикле

Если код, который может вызвать исключение, находится в цикле, можно использовать оператор continue .

for i in range(10): try: some_code_that_might_raise_exception() except: continue

continue прерывает текущую итерацию цикла и переходит к следующей, игнорируя при этом все, что осталось в теле цикла.

Вывод сообщения об ошибке

Если нужно сохранить информацию об исключении, можно вывести сообщение об ошибке и продолжить выполнение программы.

try: some_code_that_might_raise_exception() except Exception as e: print(f'Произошла ошибка: ')

В этом случае, если код в блоке try: вызовет исключение, Python выполнит блок except: , выведет сообщение об ошибке и продолжит выполнение программы дальше.

Таким образом, Python предлагает несколько механизмов для обработки исключений, позволяющих продолжить выполнение кода даже в случае их возникновения.

Источник

Suppress Exceptions in Python

In python, we normally use try-except blocks to handle exceptions in python. What if we don’t want to handle the exceptions? What if we just want to ignore the exceptions? In this article, we will discuss how we can suppress exceptions in python

Exception Handling in Python

When an exception occurs in a program, the execution of the program is abruptly interrupted. For instance, if we try to divide a number by 0, an exception will occur and the program will give the following trace-back for the exception as shown below.

num1 = 10 num2 = 0 print("The first number is:", num1) print("The second number is:", num2) output = num1 / num2 print("The output is:", output)

The first number is: 10 The second number is: 0 Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 5, in output = num1 / num2 ZeroDivisionError: division by zero

When a program is stopped abruptly, all the work done by the program will be lost. To make sure that the program executes after saving the work, we normally handle exceptions using python try-except blocks as follows.

try: num1 = 10 num2 = 0 print("The first number is:", num1) print("The second number is:", num2) output = num1 / num2 print("The output is:", output) except: print("Exception occurred.")
The first number is: 10 The second number is: 0 Exception occurred.

Here, the business logic is written in the try block, and the code to handle exceptions is written in the except block. Now, let’s see how we can suppress an exception using the try-except blocks.

Suppress Exception Using Try-Except in Python

To suppress an exception means that we will not handle the exception explicitly and it shouldn’t cause the program to terminate. Using the try-except blocks and the pass statement in python, we can suppress the exceptions in python. The pass statement is used as a null statement. When executed, it does nothing.

To suppress the exceptions, we can use the pass in the except block instead of the exception handling code. In this way, the exception will also be handled and no extra work will be done if an exception occurs. You can use the pass statement with try-except blocks to suppress exceptions in python as follows.

try: num1 = 10 num2 = 0 print("The first number is:", num1) print("The second number is:", num2) output = num1 / num2 print("The output is:", output) except: pass
The first number is: 10 The second number is: 0

Suppress Exception Using the contextlib Module in Python

Instead of using the try-except blocks and the pass statement, we can use the contextlib module to suppress exceptions in python. In this approach, we will create a context with the which statement and the suppress() function by giving the exception as an input argument to the suppress() method.

Whenever an exception will be raised inside the context, it will be automatically suppressed by the python interpreter. You can observe this in the following example.

import contextlib with contextlib.suppress(Exception): num1 = 10 num2 = 0 print("The first number is:", num1) print("The second number is:", num2) output = num1 / num2 print("The output is:", output)
The first number is: 10 The second number is: 0

Conclusion

In this article, we have discussed two ways to suppress exceptions in python. To know more about programming in python, you can read this article on list comprehension in python. You might also like this article on dictionary comprehension in python.

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Источник

try Without except in Python

try Without except in Python

Exceptions in Python are the errors detected during the execution of the code. Different types of exceptions are NameError , TypeError , ZeroDivisionError , OSError and more.

The try statement in Python is used to test a block of code for exceptions, and the except statement is used to handle those exceptions. When the code in the try block raises an error, the code in the except block is executed.

We can catch all the exceptions, including KeyboardInterrupt , SystemExit and GeneratorExit . This method should not be used to handle exceptions since it is a general statement and will hide all the trivial bugs.

We will discuss how to use the try block without except in Python. To achieve this, we should try to ignore the exception.

We cannot have the try block without except so, the only thing we can do is try to ignore the raised exception so that the code does not go the except block and specify the pass statement in the except block as shown earlier. The pass statement is equivalent to an empty line of code.

We can also use the finally block. It will execute code regardless of whether an exception occurs or not.

try:  a = 1/0 except:  pass finally:  print("Example") 

In the above code, if the try block raises an error, the except block will print the raised exception.

To ignore exceptions, we can use the suppress() function from the contextlib module to handle exceptions in Python

The suppress() function from the contextlib module can be used to suppress very specific errors. This method can only be used in Python 3.

from contextlib import suppress  with suppress(IndexError):  a = [1,2,3]  a[3] 

In the above example, it will not raise the IndexError .

Related Article — Python Exception

Источник

Читайте также:  Посмотреть версию php через консоль
Оцените статью