Learning Programming #2.2 Learning Java: Exceptions

Besides compiler errors which your learned about in my last post there are other 'errors' in java called exceptions.

Exceptions are "thrown" every time your program tries do to something that shouldn't be done.

For example if you try to access the 100th element of an array of the size 20 you will get an ArrayIndexOutOfBoundsException.

Other sources of exceptions are for example accessing variable of objects that haven't been assigned(i.e. that are null) you will get a NullPointerException,
or when you try to access a file that is currently being modified you get an IOException, …

Exception are always thrown at runtime because the compiler cannot keep track of every possible outcome of for example you trying to access an array.

Exceptions usually stop the program, unless they are catched. You can catch them with:

try {
    // Put the code that throws an Exception here:
}
catch(Exception someException) { // You can use other types of exceptions here like ArrayIndexOutOfBoundsException.
    // Code that is put here will be executed if the exception is thrown.
    // You don't need to put anything here.
    // If you want to see the contents of the exception you should do:
    someException.printStackTrace();
}

The Exception-catching above should be used with caution as it can disguise bugs inside your program. Do not use a try-catch if you don't know what you are doing! Don't use it if you are to lazy to fix the exception inside your code! This will lead to bugs in your program.

When an exception is thrown you will get printed a lot of information. I will explain how to resolve exceptions with a small example. Consider the following code. It gives the exception shown below:
Screenshot from 2019-06-02 10-13-15.png
If you are wondering why 2 is already out of bounds for an array of length 2 you should take a look at #1.5.
The exception name and description already tells us that somewhere in the program the index "2" of an array of length "2" is accessed, although it shouldn't be.
The structure below tells us where the exception happened(it happened in line 5 of the function getSomeValue() in the class ExceptionTest). The lines below tell us from which function the function in the previous line was called. In this case getSomeValue() was called in line 11, in addArrayValues(), which was called in line 18 in main().

If you call functions of other objects with some invalid arguments, the first function mentioned won't be inside your program, so you will need to scroll down the exception data to get data fix the invalid arguments you gave.

Task

Fix the exception by changing one character in my program.

H2
H3
H4
Upload from PC
Video gallery
3 columns
2 columns
1 column
9 Comments