Codiqo

Impara C# · lezione 48 di 61 · circa 10 minuti

Errori e test

Crea il tuo tipo di eccezione e scrivi semplici controlli automatici per le regole del negozio.

Cosa imparerai

  • Definire un'eccezione personalizzata
  • Lanciarla e intercettarla con i dettagli
  • Scrivere piccoli controlli che stampano PASS o FAIL

L'armatura di drago

Il pezzo migliore del fabbro, l'armatura di drago, costa 100 d'oro. Shop.Pay(amount) prende un prezzo direttamente dalla borsa: lancia ArgumentException per un prezzo non maggiore di 0, e NotEnoughGoldException, una classe tutta della battaglia, quando la borsa è troppo leggera, con una proprietà Needed e un messaggio che dice quanto oro manca ancora. Poi il negozio riceve qualche controllo tutto suo: un nuovo negozio di prova con 50 d'oro e un Check() che stampa PASS o FAIL per ogni regola, più Throws<T>() per controllare che venga lanciata l'eccezione giusta.

Errori che si spiegano da soli

Un'eccezione personalizzata è una classe che eredita da Exception:

class NotEnoughCoinsException(int needed) : Exception($"Need {needed} more coins") { public int Needed => needed; }

Questo usa un costruttore primario: i parametri subito dopo il nome della classe.

Test: piccoli controlli che confrontano quello che fa il codice con quello che dovrebbe fare. I progetti veri usano un framework come xUnit, ma l'idea è la stessa: prepara, agisci, verifica.

Controlli per il portafoglio

int failures = 0;
void Check(string name, bool passed)
{
    Console.WriteLine($"{(passed ? "PASS" : "FAIL")} {name}");
    if (!passed) failures++;
}

var w = new Wallet(100);
w.Spend(30);
Check("spending lowers the balance", w.Coins == 70);

try
{
    w.Spend(500);
    Check("overspending throws", false);
}
catch (NotEnoughCoinsException e)
{
    Check("overspending throws", e.Needed == 430);
}
Check("a failed spend changes nothing", w.Coins == 70);
Check("negative amounts are refused", Throws(() => w.Spend(-5)));
Console.WriteLine(failures == 0 ? "All checks passed" : $"{failures} failed");

static bool Throws(Action action)
{
    try { action(); return false; }
    catch (ArgumentException) { return true; }
}

class NotEnoughCoinsException(int needed) : Exception($"Need {needed} more coins")
{
    public int Needed => needed;
}

class Wallet(int coins)
{
    public int Coins { get; private set; } = coins;
    public void Spend(int amount)
    {
        if (amount <= 0) throw new ArgumentException("amount must be positive");
        if (amount > Coins) throw new NotEnoughCoinsException(amount - Coins);
        Coins -= amount;
    }
}

Output

PASS spending lowers the balance
PASS overspending throws
PASS a failed spend changes nothing
PASS negative amounts are refused
All checks passed

Suggerimento

Action è un tipo per "un pezzo di codice da eseguire più tardi". () => w.Spend(-5) è una lambda che non prende niente ed esegue la spesa.

Un solo Throws per ogni eccezione

static bool Throws<T>(Action action) where T : Exception è generico: T viene fissato alla chiamata, quindi Throws<NotEnoughGoldException>(...) e Throws<ArgumentException>(...) sono lo stesso metodo che controlla eccezioni diverse. where T : Exception promette che T è un'eccezione, ed è questo che fa compilare catch (T). Ogni Check restituisce anche se è passato, quindi contare i fallimenti è una riga di LINQ.

Un controllo generico

Console.WriteLine(Throws<FormatException>(() => int.Parse("ten")));
Console.WriteLine(Throws<FormatException>(() => int.Parse("10")));

static bool Throws<T>(Action action) where T : Exception
{
    try
    {
        action();
        return false;
    }
    catch (T)
    {
        return true;
    }
}

Output

True
False

Ora 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.