How do i handle errors in python?
-
Errors also know as exceptions in python. When code breaks you get errors. Check the code below:
def eh(): value = "Hello World!" + 5 print("This is an error, try again") eh()
Executing this code you see the output: Marvellous ain't it?
Traceback (most recent call last): File "/tester/PycharmProjects/PythonDemo/strings.py", line 6, in <module> eh() File "/tester/PycharmProjects/PythonDemo/strings.py", line 3, in eh value = "Hello World!" + 5 TypeError: Can't convert 'int' object to str implicitly
The error was expected because we received that type error. TypeError: Can't convert 'int' object to str implicitly
To make it a bit more human-friendly we can use the python try: and except: block
def eh(): try: value = "Hello World!" + 5 except: print("This is an error, try again") eh()
If you run the code now: you will see this message:
This is an error, try again
You can be more specific about capturing the error and customise your message appropriately, check the following code, the except TypeError is capture and the message is printed, if a syntax error is captured, the second except is printed.
def eh(): try: value = "Hello World!" + 5 except TypeError: print("This is a Typerror, you cannot add a string and int without first converting") except SyntaxError: print("This is an error, try again") eh()
The output is:
This is an Typerror, you cannot add a string and int without first convertingIf we test the second except, by removing the "+ 5" from the value variable and adding an eval method.
def eh(): try: value = "Hello World!" eval('5 === 4') except SyntaxError: print("This is an error, try again") except TypeError: print("This is an TypeError, you cannot add a string and int without first converting") eh()
The output is:
This is an error, try again
© Lightnetics 2024