Python raise exception or return none

By On Wednesday, October 12th, 2022 Categories : Tanya Jawab

Python raise exception or return none – Apa kabar kawan kawan semua, Selamat datang di halaman blog Trend Wisata ini. Pagi ini, kita di situs Trend Wisata dot com ingin membagikan tips yang mantap yang menjelaskan tentang Python raise exception or return none. Ini dia ibu dan bapak menyimaknya dibawah ini:

Why? Because it’s error-prone and confusing to the caller

Photo by Alexander Popov on Unsplash

Often, when reading Python code, you’ll come across utility functions that will return None. Although it might seem natural to return None in some cases, it should be avoided because it can be error-prone.

Let’s See Why Returning None Is Error-Prone

Let’s say you want to write a simple library function that divides two numbers.

The function returns None when the denominator is 0. This makes sense
as the result is undefined so sending None sounds natural. However, the user of the function can incorrectly use it as shown below.

When the numerator is 0, the function would return 0, which is expected but look at what happens in the if statement.

It’s looking for a Falseequivalent and would execute incorrectly, telling the user that your inputs are invalid which is not true!Evaluating the
response in an if condition like this is error-prone.

What Should Be Returned Instead?

The correct way would be to throw an exception in the library function as shown below.

This way, the caller of the function is responsible for handling invalid use cases by catching the exception instead and taking
appropriate action. There is no guesswork or any assumptions made by the caller and the outcome is clearer.

for folder in folders:
   try:
   latest = getLatestPdfFromFolder(folder)
results = somefuc(latest)
except IOError: pass

Honestly, though, it’s always a judgment call, and the situation you’re describing, where the called function receives an error it can’t help, is an excellent reason to re-raise an exception that is meaningful. You have the exact right idea, but unless you’re exception is going to provide more meaningful information in a stack trace than

AttributeError: 'NoneType'
object has no attribute 'foo'

example function when returning None will be:

def latestpdf(folder: str) - > Union[str, None]

and when raising an exception will be:

def latestpdf(folder: str) - > str

Suggestion : 2

An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.,Exception chaining happens automatically when an exception is raised inside an except or finally section. This can be disabled by using from None idiom:,Even if a statement or expression is syntactically correct,
it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:,The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception). If an exception class is
passed, it will be implicitly instantiated by calling its constructor with no arguments:

>>> while True print('Hello world')
File "<stdin>", line 1
   while True print('Hello world')
   ^
   SyntaxError: invalid syntax
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      ZeroDivisionError: division by zero
      >>> 4 + spam*3
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
            NameError: name 'spam' is not defined
            >>> '2' + 2
            Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
                  TypeError: can only concatenate str (not "int") to str
>>>
while True:
   ...
   try:
   ...x = int(input("Please enter a number: "))
   ...
   break ...except ValueError:
   ...print("Oops!  That was no valid number.  Try again...")
   ...
...except(RuntimeError, TypeError, NameError):
   ...pass
class B(Exception):
   pass

class C(B):
   pass

class D(C):
   pass

for cls in [B, C, D]:
   try:
   raise cls()
except D:
   print("D")
except C:
   print("C")
except B:
   print("B")
import sys

try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
   print("OS error: 0".format(err))
except ValueError:
   print("Could not convert data to an integer.")
except BaseException as err:
   print(f "Unexpected err=, type(err)=")
raise

Suggestion : 3

It’s a good practice to raise an exception instead of returning None in special cases.,When you catch an exception in the except clause, you need to place the exceptions from most specific to the least specific in terms of exception hierarchy.,When
you want to catch any exception, you can use the bare exception handlers. A bare exception handler does not specify an exception type:,In the except clause, you place the code that handles a specific exception type. A try statement can have zero or more except clauses. Typically, each except clause handles different exception types in specific ways.

To handle exceptions, you use the try statement. The try statement has the following clauses:

.wp-block-code 
	border: 0;
	padding: 0;


.wp-block-code > div 
	overflow: auto;


.shcb-language 
	border: 0;
	clip: rect(1px, 1px, 1px, 1px);
	-webkit-clip-path: inset(50%);
	clip-path: inset(50%);
	height: 1px;
	margin: -1px;
	overflow: hidden;
	padding: 0;
	position: absolute;
	width: 1px;
	word-wrap: normal;
	word-break: normal;


.hljs 
	box-sizing: border-box;


.hljs.shcb-code-table 
	display: table;
	width: 100%;


.hljs.shcb-code-table > .shcb-loc 
	color: inherit;
	display: table-row;
	width: 100%;


.hljs.shcb-code-table .shcb-loc > span 
	display: table-cell;


.wp-block-code code.hljs:not(.shcb-wrap-lines) 
	white-space: pre;


.wp-block-code code.hljs.shcb-wrap-lines 
	white-space: pre-wrap;


.hljs.shcb-line-numbers 
	border-spacing: 0;
	counter-reset: line;


.hljs.shcb-line-numbers > .shcb-loc 
	counter-increment: line;


.hljs.shcb-line-numbers .shcb-loc > span 
	padding-left: 0.75em;


.hljs.shcb-line-numbers .shcb-loc::before 
	border-right: 1px solid #ddd;
	content: counter(line);
	display: table-cell;
	padding: 0 0.75em;
	text-align: right;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	white-space: nowrap;
	width: 1%;
try:
    # code that you want to protect from exceptions
except <ExceptionType> as ex:
    # code that handle the exception
finally:
    # code that always execute whether the exception occurred or not
else:
    # code that excutes if try execute normally (an except clause must be present)Code language: Python (python)

If you have the same logic that handles different exception types, you can group them in a single except clause. For example:

try:
...
except <ExceptionType1> as ex:
   log(ex)
   except <ExceptionType2> as ex:
      log(ex)Code language: Python (python)

Become

try:
...
except (<ExceptionType1>, <ExceptionType2>) as ex:
      log(ex)Code language: Python (python)

Suggestion : 4

By Bernd Klein. Last modified: 29 Jun 2022.

n = int(input("Please enter a number: "))
while True:
   try:
   n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
   print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")
def int_input(prompt):
   while True:
   try:
   age = int(input(prompt))
return age
except ValueError as e:
   print("Not a proper integer! Try it again")
def dog2human_age(dog_age):
   human_age = -1
if dog_age < 0:
   human_age = -1
elif dog_age == 0:
   human_age = 0
elif dog_age == 1:
   human_age = 14
elif dog_age == 2:
   human_age = 22
else :
   human_age = 22 + (dog_age - 2) * 5
return human_age
age = int_input("Age of your dog? ")
print("Age of the dog: ", dog2human_age(age))
Not a proper integer!Try it again
Not a proper integer!Try it again
Age of the dog: 37

Suggestion : 5

If your error handling code
returns a value in the except block, the code that comes after that does not execute.,If you are not using finally statement, and there is an error in the except block, everything after that is not going to be executed.,If you use a continue statement in an error-handling code in a loop, any code after continue does not get executed.,The point of the finally statement in Python error handling is to ensure a piece of code executes no matter what.

1._

try:
something()
except:
   return None
something_else() # This does not get executed

But by placing it inside a finally block, it gets executed no matter what:

try:
something()
except:
   return None
finally:
something_else() # Always gets executed

For example, let’s return a value from the function if an exception occurs.

def without_finally():
   try:
   print(x)
except:
   print("There was an error")
return None
print("Yay")

without_finally()

Is it good practice to return none in Python?

Whether or not to return None explicitly is a personal decision. However, you should consider that in some cases, an explicit return None can avoid maintainability problems. This is especially true for developers who come from other programming languages that don’t behave like Python does.

Does raising an exception stop execution Python?

When an exception is raised, no further statements in the current block of code are executed. Unless the exception is handled (described below), the interpreter will return directly to the interactive read-eval-print loop, or terminate entirely if Python was started with a file argument.

What is the point of raising an exception in Python?

While syntax errors occur when Python can’t parse a line of code, raising exceptions allows us to distinguish between regular events and something exceptional, such as errors (e.g. dividing by zero) or something you might not expect to handle.

What does raise () do in Python?

Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.

Python raise exception or return none | admin | 4.5
shopee flash sale gratis ongkir
x