< previous | Table of Contents | next> |
3.6 SYNTAX ERRORS AND EXCEPTIONS
Errors can broadly be categorized into two types: syntax errors and logical errors, known as exceptions.
SYNTAX ERRORS
Syntax errors are uncovered before the code is executed. The code is first checked by the Python interpreter to determine whether it is syntactically correct. Syntax errors include incorrect punctuation, misspelled keywords, illegal variable names, incorrect indentation, etc. The code won’t execute unless the code follows Python’s syntax rules correctly.
if x == 1 print("x is 1")
The above code will raise a syntax error (SyntaxError: invalid syntax) because it is missing a colon (:) after the if condition.
Here's a Thonny example to illustrate what it would look like in practice. As you've seen in previous examples, the IDE will communicate the cause of the problem to you so you can trace it and fix it. In this case, it highlights that the colon after the if-statement
condition is missing.
The program starts running after the source code has been parsed and no syntax errors are uncovered. The errors that occur when the program is running are logical errors, otherwise known as exceptions.
EXCEPTIONS AND TRY-EXCEPT
After the Python interpreter has determined that the code follows Python’s syntax rules, the code starts executing. Exceptions, also known as logical errors, are errors detected during the execution of the program.
Exceptions are commonly caused by, for example, dividing by zero, trying to open a file that doesn't exist, trying to create an existing file, type mismatches, etc. To resolve exceptions, we can use try
and except
blocks to catch and respond to the errors, thus allowing the program to continue running.
When you anticipate a potential error, such as converting user input, you wrap it in a try
block. The try
block contains the code that Python will attempt to execute. If an error occurs within this block, instead of halting the program, Python looks for an except
block following it. If no errors exist, the try
block will execute and conduct the desired action. In this case, the except
block would not be triggered.
The except
block catches exceptions raised in the try
block and allows to handle them without stopping the program execution. You can specify the type of exception to catch, such as ValueError
and TypeError
. If an exception is raised in the try
block that matches an exception type specified in an except
block, the code within that except
block is executed.
input_string = input("Please enter an integer: ") try: # Attempt to convert the input to an integer integer_value = int(input_string) print("This is the integer value: " + integer_value) except ValueError: # Handle the case where the input cannot be converted print("ValueError. That was not a valid number.") quit() # So that the faulty program does not continue executing.
The try block contains the code that attempts to convert this input to an integer using int(user_input)
. If the user enters something that cannot be converted to an integer, for example, a word or a character, a ValueError
is raised. The except ValueError
block catches this specific exception and executes its code, printing an error message to inform the user of the mistake.
KEY THINGS TO REMEMBER
- Syntax errors prevent Python from interpreting the code and are uncovered before the code can execute.
- Exceptions are logical errors, such as type mismatches and dividing by zero. They are detected when the program is running.
- You can use
try-except
blocks to catch and handle errors, helping keep the program running even when facing an error.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next> |