Impara Java · lezione 44 di 61 · circa 8 minuti
Eccezioni
Controlla i buoni snack: lancia e cattura eccezioni, usa finally e crea un tuo tipo di eccezione.
Cosa imparerai
- Lanciare un'eccezione
- Catturarla con try/catch
- Definire un'eccezione personalizzata
I buoni snack
I clienti consegnano buoni snack: POP vale $4.50 e SODA $3.00. redeem(code) restituisce il valore di un buono, ma per alcuni codici non c'è un numero sensato: un codice che finisce con -OLD è scaduto, quindi lancia l'eccezione della cassa, ExpiredVoucherException, e un codice sconosciuto lancia una IllegalArgumentException. Il ciclo dei buoni chiama redeem dentro try, cattura prima quelli scaduti e poi tutto il resto, e conta ogni buono in finally, qualunque cosa sia successa.
Throw, catch e finally
public class Main {
static void setLives(int n) {
if (n < 0) throw new IllegalArgumentException("lives can't be negative");
}
public static void main(String[] args) {
try {
setLives(-1);
System.out.println("ok");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("checked");
}
}
}Output
lives can't be negative
checkedQuando qualcosa va storto
throw new IllegalArgumentException("...") ferma il metodo e salta al catch corrispondente più vicino. finally viene sempre eseguito, con o senza errore.
Tipi predefiniti comuni: IllegalArgumentException (input sbagliato), IllegalStateException (momento sbagliato per farlo), NumberFormatException (testo che non è un numero valido). Puoi definirne uno tuo estendendo RuntimeException.
Lanciare e catturare
class InsufficientFundsException extends RuntimeException {
InsufficientFundsException(String message) {
super(message);
}
}
public class Main {
static int withdraw(int balance, int amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
if (amount > balance) throw new InsufficientFundsException("need " + (amount - balance) + " more");
return balance - amount;
}
public static void main(String[] args) {
try {
System.out.println(withdraw(50, 20));
System.out.println(withdraw(50, 80));
} catch (InsufficientFundsException e) {
System.out.println("Sorry: " + e.getMessage());
} finally {
System.out.println("Done");
}
try {
Integer.parseInt("12a");
} catch (NumberFormatException e) {
System.out.println("Not a number");
}
}
}Output
30
Sorry: need 30 more
Done
Not a numberUn'eccezione più specifica, catturata per prima
La tua eccezione può estenderne una predefinita, così diventa un tipo più specifico di quel problema. I catch vengono provati dall'alto in basso, e un catch vale anche per ogni tipo che estende il suo, quindi quello specifico deve venire prima. Al contrario, javac si rifiuta: il catch generale avrebbe già preso tutto.
Tutto esaurito, o solo posti insufficienti
class SoldOutException extends IllegalStateException {
SoldOutException(String message) {
super(message);
}
}
public class Main {
static void book(int seatsLeft, int wanted) {
if (seatsLeft == 0) throw new SoldOutException("the showing is sold out");
if (wanted > seatsLeft) throw new IllegalStateException("only " + seatsLeft + " seats left");
System.out.println("Booked " + wanted);
}
public static void main(String[] args) {
int[][] tries = {{5, 2}, {0, 1}, {3, 4}};
for (int[] t : tries) {
try {
book(t[0], t[1]);
} catch (SoldOutException e) {
System.out.println("Sold out: " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("Can't book: " + e.getMessage());
}
}
}
}Output
Booked 2
Sold out: the showing is sold out
Can't book: only 3 seats leftOra prova tu
Questa lezione è gratuita su Codiqo, con 8 domande su quello che hai appena letto. A programmare si impara programmando, quindi finisce con un breve programma che scrivi tu, che eseguiamo e controlliamo subito.