try: except: to handle the exceptions that occur while the codes run.

The format is like this:

try:
  print(x)
except:
  print("An exception occurred")

You can specify the exceptions. Here are some examples. 

list = [1, 2, 3]

try:
    index = int(input('Insert an index number.'))   # 0, 1, 2
    print(list[index]/0)
except ZeroDivisionError:              
    print('Cannot be divided into 0.')
except IndexError:                     
    print('Wrong index.')
except ValueError:                      
    print('Not a number.')

try: except: can have else: if there is no exception. 

else is opposed to except. Here is an example.

list = [1, 2, 3]

try:
    index = int(input('Insert an index number'))   # 0, 1, 2
    print('list[{0} : {1}]'.format(index, list[index]))
except Exception as err:
    print('Exception:{0}'.format(err))
else:
    print('Success')

With finally: , you will execute the code without any conditions so even though there is an exception, you will see the finally statement will be executed.

try:
    print('Hello.')
    print(param)                    
except:
    print('Exception')
finally:
    print('Execute!')

You can also use else and finally in the same code. Try will test the excepted error to occur, except will handle the error, else will be executed if there is no exception, and finally gets executed either exception is generated or not. 

def divide(x, y):
    try:
        result = x // y
    except ZeroDivisionError:
        print("You cannot divide into 0. ")
    else:
        print("Answer: ", result)
    finally: 
        print('This is always executed')

raise is to define what kind of error to raise, and the text to print to the user.

def some_function():
    num = int(input('Insert an integer from 1 to 10'))
    if num<1 or num>10:    
        raise  Exception('Invalid number.{0}'.format(num))
    else:
        print('You inserted {0}.'.format(num))

try:
    some_function()                    
except Exception as err:
    print('Exception.{0}'.format(err))

'Python' 카테고리의 다른 글

Python) Class and Method  (0) 2022.11.18
Python) Database connection with Oracle  (0) 2022.11.18
Python) list  (0) 2022.11.08
Python) Control statements  (0) 2022.11.06
Python) Dictionary  (0) 2022.11.04

+ Recent posts