Programming consists of instructing a computer on what it can do and even how it can do it. However, things don’t always go as we expect and errors can arise.
In this Answer, we will learn about two types of errors that you can encounter when writing programs, syntax and semantic errors.
Let’s first understand what syntax and semantic mean in a programming language.
In programming, syntax is a set of rules that govern the structure of a program. Syntax is the basic vocabulary of the language.
The set of rules that determine the meaning of a program are known as its semantics. We can make sure that a program will produce a correct or expected result thanks to semantics.
Running a program may produce an error, and depending on which “part” of the language is affected, we can talk about syntax or semantic errors.
A programming language is very strict and unambiguous, so a syntax error occurs when we don’t respect or follow the language vocabulary. As a result, the program can’t run, and a useful error message will print instead.
Most of the time, the cause of this kind of error is fatigue or inattention.
/*** This program prints a user* info* */public class UserInfo {public static void main(String[] args) {String name = "Sarah Lifaefi";int age = 29.5;System.out.println("Your name is " + name)System.out.println("You are " + age + " old");}}
The function above won’t compile.
First, we declare an integer
variable but assign a double
value to it. Second, we have forgotten a semicolon (;
) in line 13.
This example will throw the following error message:
If you use an IDE like Eclipse, you’ll get more detail, like so:
Unlike a syntax error, a semantic error has to do with meaning. If a program contains this kind of error, it will successfully run, but won’t output the correct result.
Debugging is not that easy with a semantic error. Let’s see an example.
/*** This program prints the total benefit for the company**/public class TotalBenefit {public static void main(String[] args) {int branch1 = 250;int branch2 = 500;System.out.println("The total benefit is $" + (branch1 * branch2));}}
This program will output The total benefit is $125000
. This is incorrect; the expected output is $750
. This happens because we use a multiply (*
) sign instead of an addition (+
) sign.
Syntax refers to what is valid for a program to run (or compile), while semantic is about the meaning or logic.
When we write a program, errors can arise. If the errors concern the syntax, we call them syntax errors, and if the errors concern the semantics, we call them semantic errors.