Tipos de Dados e Exceções em Java
Jim White
Java Developer
Error é um problema graveimport 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 que não são subclasses de RuntimeException são checked exceptionsFileNotFoundException)RuntimeException é a superclasse de todas as unchecked exceptionsIndexOutOfBoundsException)ArithmeticException)| Subclass de RuntimeException | Quando é lançada |
|---|---|
| ArithmeticException | Cálculos inválidos, como dividir por 0 |
| IndexOutOfBoundsException | Índice usado em array, String etc. fora do intervalo |
| NegativeArraySizeException | Tentar criar um array com tamanho negativo |
int y = 5/0; // Código que causa ArithmeticException
int[] list = new int[-1]; // Código que causa NegativeArraySizeException
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
Tipos de Dados e Exceções em Java