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.
Este exercício faz parte do curso
Data Types and Exceptions in Java
Instruções do exercício
- 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 todoWorkcausing 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.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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);
}
}
}