Salve a tutti, come si può realizzare una Exception personalizzata per esempio per segnalare all'utente di aver inserito due volte uno stesso valore?
Grazie
Salve a tutti, come si può realizzare una Exception personalizzata per esempio per segnalare all'utente di aver inserito due volte uno stesso valore?
Grazie
DoubleInsertException.java
Demo:codice:package org.gengi.exceptions; public class DoubleInsertException extends Exception{ private Object value; public DoubleInsertException(Object value) { this.value = value; } @Override public String toString() { return "DoubleInsertExecption: double insert of value " + value.toString(); } }
ecco a te.codice:package org.gengi.exceptions; import java.util.ArrayList; import java.util.List; public class Demo { static List<Integer> values = new ArrayList<Integer>(); static void insert(int number) throws DoubleInsertException{ if(values.contains(number)){ throw new DoubleInsertException(number); } values.add(number); } public static void main(String[] args){ try { insert(1); insert(1); } catch (DoubleInsertException ex) { ex.printStackTrace(); } } }
Gengi
A dire il vero sarebbe meglio sfruttare il "message" (getMessage() di Throwable) nella eccezione, anche perché oltretutto toString() in Throwable è già implementato per comporre la stringa con il tipo eccezione + messaggio.Originariamente inviato da Gengi
codice:public class DoubleInsertException extends Exception{ private Object value; public DoubleInsertException(Object value) { this.value = value; } @Override public String toString() { return "DoubleInsertExecption: double insert of value " + value.toString(); } }
Quindi semplicemente:
codice:public class DoubleInsertException extends Exception { public DoubleInsertException(Object value) { super("double insert of value " + value); } }
Andrea, andbin.dev – Senior Java developer – SCJP 5 (91%) • SCWCD 5 (94%)
java.util.function Interfaces Cheat Sheet — Java Versions Cheat Sheet
Ma sii, un esempio così, non sto mica a guardare tutto il concetto è quello![]()
Ok. grazie, concetto afferrato!