Data Types and Exceptions in Java
Jim White
Java Developer
Error is a serious issue or problemimport java.util.*;
public class CauseOutOfMemory {
public static void main(String[] args) {
List<Long> numbers = new ArrayList<Long>();
long counter = 0;
while (true) {
numbers.add(counter);
counter++;
}
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.lang.Long.valueOf(Long.java:1204)
at foo/exceptions.CauseOutOfMemory.main(CauseOutOfMemory.java:12)
| Checked Exception | Runtime ("unchecked") Exception | |
|---|---|---|
| Require handling | Yes | No |
| General cause | Things outside our control | Our programming mistakes |
| Recovery | Can usually recover when anticipated | Usually unrecoverable |
| Recovery mechanism | try/catch or throws | Best to code carefully to avoid them |
| Example exception | File not found | Array index out of bounds |
Exception subclasses not also subclasses of RuntimeException are checked exceptionsFileNotFoundException)RuntimeException superclass for all unchecked exceptionsIndexOutOfBoundsException)ArithmeticException)| RuntimeException Subclass | Description of when thrown |
|---|---|
| ArithmeticException | Bad arithmetic calculations like dividing by 0 |
| IndexOutOfBoundsException | Index used on an array, String, etc. is out of range |
| NegativeArraySizeException | Trying to create an array with a negative size |
int y = 5/0; // ArithmeticException causing code
int[] list = new int[-1]; //NegativeArraySizeException causing code
Exception in thread "main" java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.NegativeArraySizeException: -1
public class LoadClass {
public static void main(String[] args) {
Class myClass = Class.forName("com.mysql.Driver");
}
}
LoadClass.java:3: error: unreported exception ClassNotFoundException;
must be caught or declared to be thrown
Class myClass = Class.forName("com.mysql.Driver");
^
1 error
Data Types and Exceptions in Java