Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Data Types and Exceptions in Java

Cursus bekijken

Oefeninstructies

  • 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 an StackOverflowError.
  • After seeing the StackOverflowError, add + 1 to cycles in the call to doWork, 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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);
		}
	}
}
Code bewerken en uitvoeren