Fixing an error
Errors are serious problems in the Java world. Sometimes they are created due to environmental problems beyond our control. Other times, we may write bad code that causes an Error. In this exercise, you will observe and then correct an application that will never terminate and cause an Error (specifically, a StackOverflowError). Seeing an Error will help you identify them in the future. Unlike exceptions, errors cannot be handled with try-catch or throws.
Cet exercice fait partie du cours
Data Types and Exceptions in Java
Instructions
- Run the Sample code as is where the
cyclesvalue never changes, which leads to an infinite loop of calls and causes the application to fail and generates anStackOverflowError. - After seeing the
StackOverflowError, add+ 1tocyclesin the call todoWork, causing the cycles value to change, which will stop the infinite loop of calls. - Rerun the code to see the application successfully run and avoid the
StackOverflowError.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
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);
}
}
}