Control Flow

Try Catch Block in Python

A try-catch block is used to mitigate errors in code and prevent program crashing during runtime. It 'tries' a block of code that could give an error. If the error (exception) is raised, it will execute a different block of code rather than crash the program.


Syntax
try:
    #Code that may raise an error

    #Raising your own errors
    raise ErrorType("Error message")
except ErrorType as e: #code to run if error occurs
    #code to run if error is raised
else:
    #code to run if no error is raised

Notes

The ErrorType is the type of error which can occur. Most are defined within Python.

User-defined exceptions are created by using the raise statement and providing an error message.


Example
try:
    test_score = (int)input('What is your test score?')
    test_out_of = (int) input('What is the test out of?')
    if(test_out_of == 0):
        raise ArithmeticError("You cannot have a test out of 0!")
    test_percent = test_score / test_out_of
except ArithmeticError:
    print ("You cannot have a test out of zero!")

< Ternary Operator   |   With Statement >

© 2018 SyntaxDB. All Rights Reserved.