Errors Handling and Types of Errors
Explore the different types of errors including syntax, runtime, and logical errors in Python and PowerShell. Learn how to catch, throw, and create custom exceptions for effective error management in your scripts.
Error Handling
Handling errors or exceptional conditions is a key part of any programming language. Even small scripts and programs should ideally be written with the ability to catch exceptions and handle them gracefully in an expected manner. In this chapter, we are going to delve deeper into types of errors and how to handle them. We will learn to throw, catch, and create custom errors.
Types of Errors
Generally, there are 3 types of errors: syntax, runtime, and logical errors. Let’s look into each of these errors one at a time.
Syntax errors
In any language , the arrangement of words and phrases to create well-formed sentences is called syntax. In Computer Science, however, syntax is a structure of statements. Two important takeaway words from these definitions are “well-formed” and “structure”.
So, in any programming language, a syntax error is usually observed when the parser detects an incorrect statement or finds a programming construct like a parenthesis or bracket missing in the program. In other words, a syntax error is a grammatical error for a programming language that expects developers to provide statements in a specific structure. If this specific structure is not observed, an error will be thrown. The following are some common examples of syntax errors:
- Misspelled cmdlets, variables, or names of a function.
- Missing semicolons or improper indentation.
- Improperly matched parentheses
( ), square brackets[ ], or curly braces{ }.
Let’s see some examples to understand this better.
PowerShell
dir()
write-hst
Type these commands one by one in the terminal below to see the errors.
The first example in the above PowerShell sample uses the dir alias of the Get-ChildItem cmdlet. Since the parenthesis () was not expected after a cmdlet, we will run into syntax errors. In the second example, the Write-Host cmdlet was misspelled as write-hst which the parser couldn’t understand and thus caused another error.
Python
dir())
prnt('hello')
Type these commands one by one in the terminal below to see the errors.
The first example in the above Python sample has an extra closing parentheses ')' which was not expected, causing a 'SyntaxError: invalid syntax' to be thrown. In the second example, we misspelled the print() function so the parser couldn’t understand it prompting it to throw an 'NameError: name 'prnt' is not defined'.name 'prnt' is not defined'.
Runtime errors
Runtime errors, as the name suggests, can only occur while the program is running (assuming there are no syntax errors). Runtime errors are usually observed when the computer program is asked to perform something that it is unable to handle reliably. The following are some common examples of Runtime errors:
- File doesn’t exist
- Division by zero
Let’s see some examples to understand this better.
PowerShell
### dividing a number by zero.
1/0
### accessing a file that doesn't exist
Get-ChildItem /usercode/test.txt
Type these two commands in the following terminal one by one to see the errors.
Python
## dividing a number by zero.
1/0
## accessing a file that doesn't exist
open('/usercode/test.txt')
Type the above commands one by one below and hit the run button to see the errors.
Logical errors
In terms of computer programming, a logical error is a bug in a program that causes it to operate incorrectly or behave abnormally to produce unintended results. A logical error may not be immediately recognized because, unlike syntax or runtime errors, a logical error doesn’t terminate abnormally and is considered correct per the programming language. The following are some common examples of logical errors:
- Performing addition in place of subtraction
- Using the assignment operator
=in place of equals-to (==or-eq) - Using the wrong variable or file name.
Let’s see some examples to understand this better.
The logical error in the above example is that the else statement should not execute.The condition should evaluate to $True when the value of variable $name is equals to 5, because 5 is not less than 5.
Below is a similar implementation of the logical error in Python. It will run just fine without throwing any errors, but the result it generates is unintended and logically incorrect.
Raising an Exception or Throwing an error
Sometimes it is a requirement for a developer to explicitly raise or throw an exception so that it can be handled properly. Otherwise, the programming language may or may not throw that error.
PowerShell has a throw keyword, which can be used to create our own exception events.
Syntax:
throw [ExceptionClass] "Your Error Message"
In the following example, we raised an FileNotFoundException, which appears when no such file was found in the program.
To raise an exception from Python we have to use the raise keyword.
Syntax:
raise ExceptionClass("Your Error Message")
As in the following Python example, we raised a ValueError using the raise keyword when the numerical value did not meet specific criteria.