Python return error message

Python how to return error message in python

Solution 1: In python code, error conditions are usually indicated with exceptions. Using exception rather than return values to indicate errors has the added advantage that the exception would bubble up until it reaches a statement.

Returning error string from a function in python

Create your own exception and raise that instead:

class MyValidationError(Exception): pass def my_function(): if not foo(): raise MyValidationError("Error message") return 4 

You can then call your function as:

try: result = my_function() except MyValidationError as exception: # handle exception here and get error message print exception.message 

This style is called EAFP («Easier to ask for forgiveness than permission») which means that you write the code as normal, raise exceptions when something goes wrong and handle that later:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

if foo(self, input, error_msg): raise SomethingError("You broke it") 
try: something() except SomethingError as e: print str(e) 

It’s the Pythonic approach and the most readable.

Читайте также:  Print без пробелов python

Returning a tuple like (12, None) may seem like a good solution, but it’s hard to keep track of what each method returns if you’re not consistent. Returning two different data types is even worse, as it will probably break code that assumes a constant data type.

Python Error Handling, The easiest way to catch errors is with a Try..Except block. If the code inside the Try has an Duration: 25:05

Python Error Handling

The easiest way to catch errors is with a Try..Except block. If the code inside the Try has an Duration: 25:05

TRY EXCEPT in Python | Python Tutorial for Beginners #8

Exception Handling in Python can be done using try except in python. Handling exceptions Duration: 14:53

Python Return error from function

In python code, error conditions are usually indicated with exceptions. You could use raise ValueError(«Arrays must have the same size») .

Using exception rather than return values to indicate errors has the added advantage that the exception would bubble up until it reaches a except statement. So you can defer the error handling up to a place where it makes sense. Also exceptions have an associated descriptive message instead of a magic number.

The break statement, as in many other languages, is used to interrupt the flow in loops, like ones created with while or for .

def do_some_stuff(array1, array2): # Before doing stuff, check to ensure both arrays have the same length if len(array1) != len(array2): return -1 

Just return the error code. In this way the rest of the code of the function will not be executed.

How to get exception message in Python properly, If you look at the documentation for the built-in errors, you’ll see that most Exception classes assign their first argument as a message

How would i make a custom error message in python

Use a try-except block to capture the error and use the raise statement to say the error message of your choice:

try: a = int(input()) except: raise Exception('There has been an error in the system') 

Using try , except and raise

Since ValueError inherits from the Exception class, the first parameter when creating a ValueError object is the message it prints:

try: int("string") #the code that raises the error except ValueError: raise ValueError("Your custom message here.") 
Traceback (most recent call last): File "", line 2, in ValueError: invalid literal for int() with base 10: 'string' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 4, in ValueError: Your custom message here. 

If you don’t want the previous error chain to print, put from None in the raise statement:

try: int("string") #the code that raises the error except ValueError: raise ValueError("Your custom message here.") from None 
Traceback (most recent call last): File "", line 4, in ValueError: Your custom message here. 

I suggest you leave the chain because it gives more information, like what was inputted that raised the error. If you want to include the information from the original error in the custom message, use the error’s attributes:

from traceback import format_tb try: int("string") #the code that raises the error except ValueError as err: raise ValueError("Custom message with traceback and original message\n" + format_tb(err.__traceback__)[0] + err.args[0] + "\nEnd of error message.") from None 
Traceback (most recent call last): File "", line 4, in ValueError: Custom message with traceback and message File "", line 2, in invalid literal for int() with base 10: 'string' End of error message. 

Though this allows for customization of the error’s print, the code is a little unpythonic.

Using assert

Because in the question you said you wanted to block all strings, you can use assert and isinstance() :

obj = "a string" #the input you want to raise the error on assert not isinstance(obj, str), "Your custom message here." 
Traceback (most recent call last): File "", line 1, in AssertionError: Your custom message here. 

Though using assert looks clean, the error won’t carry as much information because it would be a generic AssertionError . Raising a ValueError tells more information about what caused the error at a glance.

You need to use a try except block to catch the error — see the documentation. Then you could just print a message, and, if necessary, exit the program:

try: value = int(input("Enter an integer: ")) except ValueError: print("There has been an error in the system.") input() # To let the user see the error message # if you want to then exit the program import sys sys.exit(1) 

Python exception message capturing, or we can directly use logger.exception() to print the exception. You can try specifying the BaseException type explicitly. However, this will

How can I throw TypeError with message inside if statement in Python?

You can use a try — except to catch the error, and throw for example another one:

def prefill(n,v): try: n = int(n) except ValueError: raise TypeError(" is invalid".format(n)) else: return [v] * n
>>> prefill(3,1) [1, 1, 1] >>> prefill(2,"abc") ['abc', 'abc'] >>> prefill("1", 1) [1] >>> prefill(3, prefill(2,'2d')) [['2d', '2d'], ['2d', '2d'], ['2d', '2d']] >>> prefill("xyz", 1) Traceback (most recent call last): File "", line 1, in prefill ValueError: invalid literal for int() with base 10: 'xyz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "", line 1, in prefill TypeError: xyz is invalid 

You do not per se need to specify an exception to raise . In case you want to re -raise the exception, simply writing raise is sufficient. You can furthermore specify a tuple of exceptions to catch, and make v optional here, for example:

def prefill(n,v=None): try: n = int(n) except (TypeError, ValueError): raise TypeError(" is invalid".format(n)) else: return [v] * n

Use the raise keyword to raise an exception, rather than return it. raise is used to generate a new exception:

>>> raise TypeError Traceback (most recent call last): File "", line 1, in TypeError 

In this example I raised the TypeError by using the exception class directly. You can also create instances of the error like this:

>>> t=TypeError() >>> raise t Traceback (most recent call last): File "", line 1, in TypeError 

Doing it that way allows various properties to be set on the object before using raise . The problem posted includes this requirement:

When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.

That is an example of a situation where it is necessary to create an instance of the error and set a message property on it before using raise . That can still be done in one line:

>>> raise TypeError("foo") Traceback (most recent call last): File "", line 1, in TypeError: foo 

To catch exceptions, use a try-except block, rather than an if block:

x = 'hello, world!' try: y = x / 2 except TypeError as e: e.args = (*e.args, str(x) + " is not valid") raise 
TypeError: ("unsupported operand type(s) for /: 'str' and 'int'", 'hello, world! is not valid') 

note that you can check the datatype of a variable using type() :

>>> x = 5 >>> type(x) >>> if type(x) == int: . print("it's an int") . it's an int 

Also, the code sample could be simplified to:

Best practice in python for return value on error vs. success, First, whatever you do don’t return a result and an error message. That’s a really bad way to handle errors and will cause you endless

Источник

Python Return Error From Function

Be on the Right Side of Change

💬 Question: How do you write a function that returns a real Python error instead of an “error code” such as -1 or None in case something got wrong?

For example, you may want to check the function input arguments for having the correct type or length (in the case of iterable arguments) before running the function body. In case your test fails, you want to return an error message.

Here’s an example where you return -1 to indicate that there has been an error, i.e., the arguments have different lengths:

def f(l1, l2): if len(l1) != len(l2): # Error Should Be Returned return -1 # Do stuff

However, returning a dummy value is not very pythonic.

Best Practice Solution

The best practice solution to indicate that there was an error in a Python function is not to return a dummy value but to raise an error using syntax such as raise ValueError(«. your message . «) .

The main advantage is that the error propagates (technical term: “bubbles up”) through the function call stack until it gets caught by an except statement.

Example: if function f() calls function g() which calls function h() which raises an error, the error will be propagated to g() and then to f() which may catch it using a try/except block.

Another advantage of raising an error is readability.

An error message points out the problem in an easy-to-understand English text message. A magic number is likely to be misinterpreted, e.g., the caller of the function may think that the magic number is the actual output of the function — and not an error code.

Example

Let’s have a look at a simplified example:

def f(l1, l2): if len(l1) != len(l2): raise ValueError("Arguments have different lengths!") # Do stuff f('hello', 'hi')

This leads to the following output:

Traceback (most recent call last): File "C:\Users\. \code.py", line 8, in f('hello', 'hi') File "C:\Users\. \code.py", line 4, in f raise ValueError("Arguments have different lengths!") ValueError: Arguments have different lengths!

This leads us to the following question:

How to Catch the Error?

To catch the error and avoid that the error terminates your whole program, you need to catch it using a try/except block.

Источник

Оцените статью