Common exceptions you will see
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A few exceptions cause most crashes in beginner programs. They are Java's built-in exceptions: classes Java already has, each named for what went wrong, so knowing them makes a stack trace quick to read.
Dividing by zero: ArithmeticException
The class average for 0 students crashes the marks app. ArithmeticException is thrown when a whole number (int or long) is divided by 0 with / or %.
int total = 450;int students = 0;int avg = total / students; // ArithmeticException: / by zeroint left = total % students; // the same exceptiondouble avg2 = 450.0 / students; // Infinity, no exceptionA double division by 0 gives Infinity, as in Arithmetic operators (opens in a new tab). That is no better: it is a wrong answer that does not even stop the program, so check the count either way.
Experiment
Division by zero lab
Set students to 0, then back to 5. Compare the int and the double division.
- total / students
- 90
- total % students
- 0
- (double) total / students
- 90.0
A bad index: arrays and strings
Asking for the 4th mark of 3 crashes. ArrayIndexOutOfBoundsException is thrown for an array index below 0 or not less than the length; StringIndexOutOfBoundsException is the same for the letters of a string.
int[] marks = {78, 85, 62};System.out.println(marks[3]); // ArrayIndexOutOfBoundsExceptionString code = "abc";System.out.println(code.charAt(5)); // StringIndexOutOfBoundsExceptionBoth messages name the bad index and the length, like Index 3 out of bounds for length 3. substring with an end past the length, such as "abc".substring(0, 5), throws StringIndexOutOfBoundsException too. Review: Index outside the array (opens in a new tab).
No object: NullPointerException
A form leaves the city blank and the program crashes on city.toUpperCase(). null means a variable holds no object at all; calling a method on it throws NullPointerException, often called NPE.
Example 1 · Calling a method on null
public class NullCity { public static void main(String[] args) { String city = null; System.out.println("Checking city"); System.out.println(city.toUpperCase()); }}Checking city Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "city" is null at NullCity.main(NullCity.java:5)
What this code does
cityholdsnull, so there is no text to turn into capitals.- The message names the method and the variable that was
null. (Some setups show"<local1>"instead of the namecity.)
null is not the same as empty text: "".length() is 0, but null has no length at all, so city.length() throws too.
Text that is not a number
A user types abc for their age. NumberFormatException is thrown when Integer.parseInt gets text that is not a whole number; InputMismatchException is thrown when Scanner's nextInt() reads such text.
Example 2 · Typing "abc" for age
public class AgeCrash { public static void main(String[] args) { String ageText = "abc"; System.out.println("Converting " + ageText); int age = Integer.parseInt(ageText); System.out.println("Next year: " + (age + 1)); }}Converting abc Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:665) at java.base/java.lang.Integer.parseInt(Integer.java:781) at AgeCrash.main(AgeCrash.java:5)
What this code does
- The message quotes the text that failed:
For input string: "abc". - The first
atlines are inside Java's own code (java.base/...). Skip them; their numbers depend on your Java version. - The last line has your class name: the problem is on line 5, the
parseIntcall."12.5"and" 25"(with a space) fail the same way.
InputMismatchException lives in java.util, like Scanner. Review: Text where a number is expected (opens in a new tab).
Prevent them with a check
Often you know the bad case in advance: a count of 0, an index past the end, a null text. An if that checks the value before the risky line means the exception never happens.
Example 3 · Check first, then use
public class SafeChecks { public static void main(String[] args) { int[] marks = {78, 85, 62}; int index = 5; if (index >= 0 && index < marks.length) { System.out.println("Mark: " + marks[index]); } else { System.out.println("No subject at index " + index); } String city = null; if (city != null) { System.out.println(city.toUpperCase()); } else { System.out.println("City not given"); } }}No subject at index 5 City not given
What this code does
- Each
ifchecks the value before the risky line, somarks[5]andcity.toUpperCase()never run. - The
elsegives the user a clear message instead of a stack trace.
Classify
Name the exception
Tap a line of code, then tap the exception it throws.
Next step
Check your understanding
8 quick questions