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.
This exercise is part of the course
Data Types and Exceptions in Java
Exercise instructions
- 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
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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);
}
}
}