The first and most obvious thing we need to learn about programming are the details of our programming languge, Java in our case. However as programmers have had to discover since the very beginning of programming, even when we know all those details, it can sometimes be frustratingly tricky to get our programs working correctly.
The informal term for anything that makes a program not work correctly is bug and the process of getting all the bugs out of a program is called debugging. The term bug predates computers by at over half a century, at least. Thomas Edison wrote about working out the โbugsโ in his inventions in 1878. And it made its way into engineering and from there into the world of computers so that when opererators working under Grace Hopper on the Harvard Mark II computer in 1947 found an actual bug (a moth) inside the computer they taped it into the logbook with the note โFirst actual case of bug being found.โ
But bugs and debugging really came into their own with the invention of software. You might think that with no physical parts to break down or get jammed and no wires to be crossed, it would be simple to make software work. After all the computer just does what we tell it, right? Alas, it was no not to be, as Maurice Wilkes recounts discovering when working on EDSAC, one of the earliest stored-program computers in the world which came online in 1949:
As soon as we started programming, we found out to our surprise that it wasnโt as easy to get programs right as we had thought it would be. Debugging had to be discovered. And I can remember the exact instant where I wasโour tape equipment was on one floor, the computer was on the other, and and I was passing down from the computer to make a change in my program tapeโand in that instant I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.
The first kind of bug we need to deal with are called syntax errors. These are the programming equivalent of typos in English and usually come from the same cause: misplaced or missing punctuation, misspelled words, and incorrect capitalization. However, unlike in English, where we can still understand text even if it contains a misplaced comma or two, when a program does not exactly follow the rules of Java, it canโt be run at all.
In Java running a program actually happens in two steps; first we compile it and that produces a set of files that Java can then run. Errors that are detected during compilation mean we donโt get the runnable files so we so we have to fix them before we can even run our program. These are also called compile-time errors because they are detected by the compiler.
The good news is the Java compiler will tell you if your Java code is not exactly right. Examples of syntax errors are a semicolon ; missing or if the code has a open curly brace { or open quote ", but no close curly brace } or close quote ".
The more code you write and the more syntax errors you create and then remove, the more you will learn which details you really need to pay attention to. To get some practice at creating syntactically correct code try the following two exercises.
The following has all the correct code to print out โHi my friend!โ when the code is run, but the code is mixed up. Drag the blocks from left to right and put them in the correct order. Click on the โCheck Meโ button to check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks. After three incorrect attempts you will be able to use the Help Me button to make the problem easier.
The following has all the correct code to print out โHi there!โ when the code is run, but the code is mixed up and contains some extra blocks with errors. Drag the needed blocks from left to right and put them in the correct order. Click on the โCheck Meโ button to check your solution.
In this book when you press the Run button on coding exercises, the code is first complied and then run. But if the code has syntax errors or other compile-time errors, you will see error messages displayed below the code.
In the exercises below, you will click the run button to compile and run the code. Unfortunately you will find that the initial code in each exercise contains at least one syntax error that you need to fix.
It will be a lot easier to find the problems if you understand a few basics about how to read the error messages. They arenโt always easy to understand but knowing how theyโre structured can help so letโs take a closer look.
The first line starts with the name of the file that was being compiled. (When we run code in this book we donโt name the file but it will be named to match the name of the class.) Then thereโs a colon (:) followed by a number. That number tells us the line number in the file where the compiler detected the error, in this case line 5.
Error messages arenโt always 100% accurate about where the error actually is; sometimes we actually need to change something a bit earlier in the program and sometimes a bit later. But the line the compiler is pointing us at is the best place to start looking.
After the line number and another colon, we will find the actual error message. These can be kind of cryptic but you should still read it. As you learn more Java vocabulary they will become more meaningful but they almost always contain some useful clues. For instance take this error message: โunclosed string literalโ. You may not know what a string literal is (yet) but โunclosedโ suggests something was opened and then not closed. Keep that thought in mind.
Now look at the next two lines. The very next line is just the line of code from your program. But below that is a very important line containing a single caret (^) positioned to point at exactly where in the line the Java compiler thinks the problem is. In this case itโs pointing at the quotation mark (") before โHiโ. So itโs complaining about something being unclosed and itโs pointing us at a quotation mark. Usually quotation marks come in pairs called the open quote and the close quote, right? And if you look at the line of code youโll see that thereโs no closing quotation mark. Could that be the problem? Try adding a quotation mark and see if that fixes it!
It is worth getting in the habit of really reading error messages. The people who wrote the Java compiler put in lot of work to try to make the error messages useful. If you read them, youโll soon learn to recognize common mistakes and will get much quicker at finding your syntax errors.
Another thing that happens sometimes is after we fix one syntax error, weโll get a new syntax error. This is because sometimes the compiler canโt even detect the second error until the first one is fixed.
Which is another reason itโs important to read error messages! Itโs very tempting when we see that thereโs an error to jump immediately to trying to fix it. Arg, an error! Get rid of it! But if we donโt slow down and read the message in a case like this, we might not notice that weโve actually fixed the first error. And if we donโt notice that we fixed it, we might undo our change and unfix it!
Click the run button to try to run the following code. Look for an error message after the code. This time the error message will probably point even more exactly at the problem than in the previous exercise. Try to fix the code and run it again.
Click on the run button below to try and run the following code. What is wrong this time? The first error message will probably point you directly at the problem. But after you fix that youโll probably get a new error! A hint for the second error: capitalization matters.
Some errors cannot be detected by the compiler. These are called run-time errors. These errors occur when the program is running, after the code is compiled. They can be caused by a variety of things, such as dividing by zero or trying to read from a file that doesnโt exist or a logic error in the code.
An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the programโs execution. Java will sometimes report an exception with a message that tells you what went wrong. For example, if you try to divide by zero, Java will throw (report) an ArithmeticException while running. Try this out in the code below.
The following code has a run-time error. When you click on run, the compiler will not catch it since it is not a syntax error. The program will run and try to compute 3 divided by 0 which cannot be computed. This will cause a run-time error, and the program will report an ArithmeticException. Try it out!
Run-time errors can be difficult to find because they donโt always cause the program to crash. Sometimes they just cause the program to behave in unexpected ways because of an error in the logic. A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly causing a run-time error. For example, a programmer might have made a math mistake so the wrong value is calculated. Logic errors can be detected by testing the program with specific data to see if it produces the expected outcome. Weโll see an example of this after learning about expressions in the next lessons.
Watch the following video to see that all coders get bugs. Debugging is a normal part of coding. It can be frustrating at times, but you will get better at it with practice! Sometimes another pair of eyes really helps, so ask a friend if you get stuck or try explaining your code line by line to someone or even a rubber duck. Rubber duck debugging is a lot of fun!
In this course, you are encouraged to work together in pairs to complete the programming challenges. Pair programming is a successful software development technique where two programmers work together at one computer. One, the driver, types in code while the other, the navigator, gives ideas and feedback. The two coders switch roles frequently. Another option is buddy programming, where two or three coders work on their own computers but help each other as needed. If youโre working alone, you may want to explain the code to a rubber duck or another toy using Rubber duck debugging.
A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the programโs execution.
System.out.println("Roses are red, ") // Line 1;
System.out.println("Violets are blue, ") // Line 2;
System.out.println("Unexpected '}' on line 32. ") // Line 3;
The code segment is intended to produce the following output but may not work as intended.