Throwing exceptions
When something goes wrong, the program throws an exception. This is because someone that created Java or the library that you are using, at some point, coded it that way. A lot of the Java library is programmed to throw exceptions, such as in the following situations:
- When you try to access a field or method on a null instance,
NullPointerException
- When you try to divide by 0,
ArithmethicException
- When you try to access an index in an array that is not part of the array,
ArrayIndexOutOfBoundsException
Here’s an example of the output of code that throws an exception:
int x = 2 / 0;
This is the output:
Exception in thread "main" java.lang.ArithmeticException: /by zero at ThrowingExceptions.main(ThrowingExceptions.java:3)
You can see the name of the exception in the output (java.lang.ArithmeticException
), as well as the message, stating /
by zero
.
Underneath the exception, we can see the...