By Tony Bevis on Saturday, 07 October 2023
Category: Java

Java programming course: 2.3 Dealing with errors

In the previous lesson you learnt how to create objects.

Dealing with errors

Errors in Java programs can be categorised into two types:

  1. Errors that stop the class from being compiled.
  2. Errors where the program compiles successfully but does the wrong thing when it runs.

There are two categories of reason why a class won't compile: syntax errors and semantic errors:

To resolve a syntax or semantic error you need to look at the message(s) provided by the compiler. It is generally caused by a typing error or spelling mistake.

Errors where the class compiles but does the wrong thing when run are known as logical errors:

To resolve a logical error is often harder, and you may have to trace through each statement to spot where it is going wrong. See if you can spot the error in the following method:

Hopefully you can see that the sum is being multiplied by 3 when it should instead be multiplied by 2. If you are unable to spot the logical error by just looking at the code, then a good technique is to send pertinent values to output at particular stages using System.out.println():

Doing the above should help you locate where the error is, since you will see that sum is correct but twiceSum is incorrect, so you only need to look at the line(s) of code that precede the incorrect location.

A logical error in a piece of software is known as a bug, so resolving errors is known as debugging. There are more sophisticated debugging techniques involving breakpoints and assertions, which will be covered later in the course.

In the next lesson you will see how to use the provided Java APIs.

Lesson 2.4 Java APIs

Related Posts

Leave Comments