Java exceptions

André Silva
3 min readApr 10, 2020

A program can fail for just about any reason. It’s normal.

Coding mistakes like trying to access an invalid index in an array or calling a method with a value that the method doesn’t support. Some of these are coding mistakes, others are completely beyond your control. What can we do to deal with this situations?

Exceptions!

An exception is Java saying:

I don’t know what to do now!

Following scenario..

public class Salary { 

public static void main(String[] args) {

System.out.println(args[0]);
System.out.println(args[1]);
}
}

Then try to call it without enough arguments:

javac Salary.java
java Salary 100

On the line System.out.println(args[1]) java realize there’s only one element in the array and index 1 is not allowed.

Java will say “I don’t know how to handle it” and throws up its hands in defeat and throw an exception.

java.lang.ArrayIndexOutOfBoundsException: 1

Exceptions can and do occur all the time, even in solid program code and when it happens remember, exceptions alter the program flow every time them occur.

To understand exceptions we need to know about Throwable superclass:

--

--