Basic Python

try, except, else, finally, sys.stderr, raise

Naranjito 2020. 12. 16. 12:30

Following the previous post I took the big data with elastic search(

2020/12/09 - [Analyze Data] - Import the data with Elasticsearch in Python

), how should I do if I encounter Error I could't fix it over the code?

 

  • Containing the error into try, except syntax
    #it occurs Index error when it executes nix, so try it until execute 
    try:
        nxt = res["hits"]["hits"][-1]["sort"][0]
        print(tot_len)

    #and if it encounter the index error, return the error message
    except IndexError as err:
        print("IndexError: ", err)
        break
try:
    실행 코드
except:
    예외가 발생했을 때 수행할 코드
else:
    예외가 발생하지 않았을 때 수행할 코드
finally:
    예외 발생 여부와 상관없이 항상 수행할 코드
per = ["10.31", "", "8.00"]

for i in per:
    try:
        print(float(i))
    except ValueError as err:
        print(err)
    else:
        print('go through')
    finally:
        print('final')
        
>>>
10.31
go through
final
could not convert string to float: ''
final
8.0
go through
final
def converts(s):
    try:
        a=int(s)
        print('success')
    except (ValueError,TypeError) as e:
        print(e, file=sys.stderr)
        raise ValueError('wrong wrong wrong')
    else:
        print('no error')
    finally:
        print('unconditionally')

 

  • sys.stderr

System.Standard Error, the interpreter's own prompts and its error message go to stderr.

def converts(s):
    try:
        a=int(s)
        print('success')
    except (ValueError,TypeError) as e:
        print(e, file=sys.stderr)
        a=-1
        return a
converts(sys.argv[1])
>>>
invalid literal for int() with base 10: '--ip=127.0.0.1'
-1

 

  • raise

Raise an error.

def converts(s):
    try:
        a=int(s)
        print('success')
    except (ValueError,TypeError) as e:
        print(e, file=sys.stderr)
        raise ValueError('wrong wrong wrong')
        
from math import log 
def string_log(s):
    converts(s)
    return log(s)
    
string_log([1,2,3])
>>>
int() argument must be a string, a bytes-like object or a number, not 'list'
...
ValueError: wrong ValueError