Fixing an error
Errors are serious problems in the Java world. Sometimes they are created because of environmental problems outside of our control. Other times, we may write bad code that causes the Error
. In this exercise, you will see and then fix an application that will not ever end and cause an Error
(a StackOverflowError
). Seeing an Error
will help you identify them in the future. Unlike exceptions, errors cannot be handled with try-catch or throws.
Diese Übung ist Teil des Kurses
Data Types and Exceptions in Java
Anleitung zur Übung
- Run the Sample code as is where the
cycles
value never changes, which leads to an infinite loop of calls and causes the application to fail and generates anStackOverflowError
. - After seeing the
StackOverflowError
, add+ 1
tocycles
in the call todoWork
causing the cycles value to change, which will stop the infinite loop of calls. - Rerun the code to see the the application successfully run and avoid the
StackOverflowError
.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
public class ErrorGeneration {
public static void main(String[] args) {
System.out.println("Started the work");
doWork(0);
System.out.println("Work complete");
}
public static void doWork(int cycles) {
if (cycles < 10) {
// Add +1 to cycles after running
doWork(cycles);
}
}
}