C# Exception Handling Beheersen: Strategieën & Best Practices
Exceptions bieden een manier om controle over te dragen van één deel van het programma naar een ander. C# exception handling bouwt op vier sleutelwoorden: try, catch, finally, throw.
- try – Identificeert codeblok waar exceptions geactiveerd worden. Volgt door catch-blokken.
- catch – Vangt exception op op de gewenste plaats.
catchmarkeert het opvangen. - finally – Voert statements uit, of er nu een exception is of niet (bijv. bestand sluiten).
- throw – Gooit exception wanneer probleem optreedt.
Syntaxis
try {
// statements die exception veroorzaken
} catch(ExceptionNaam e1) {
// foutafhandeling
} catch(ExceptionNaam e2) {
// foutafhandeling
} finally {
// statements die altijd uitgevoerd worden
}
Meerdere catch blokken voor verschillende exception-types.
Exception Klassen in C#
Exceptions zijn klassen, afgeleid van System.Exception. Belangrijke basisklassen: System.ApplicationException (programmeur-gedefinieerd) en System.SystemException (systeem-exceptions).
| Nr | Exception Klasse & Beschrijving |
|---|---|
| 1 | System.IO.IOException – I/O fouten. |
| 2 | System.IndexOutOfRangeException – Array index buiten bereik. |
| 3 | System.ArrayTypeMismatchException – Type mismatch met array. |
| 4 | System.NullReferenceException – Null object referentie. |
| 5 | System.DivideByZeroException – Delen door nul. |
| 6 | System.InvalidCastException – Typecasting fout. |
| 7 | System.OutOfMemoryException – Onvoldoende geheugen. |
| 8 | System.StackOverflowException – Stack overflow. |
Exceptions Afhandelen
Gestructureerde oplossing met try, catch, finally.
Voorbeeld: Delen door Nul
using System;
namespace FoutAfhandelingsApplicatie {
class DeelGetallen {
int resultaat;
DeelGetallen() { resultaat = 0; }
public void Deling(int num1, int num2) {
try {
resultaat = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception gevangen: {0}", e);
} finally {
Console.WriteLine("Resultaat: {0}", resultaat);
}
}
static void Main(string[] args) {
DeelGetallen d = new DeelGetallen();
d.Deling(25, 0);
Console.ReadKey();
}
}
}
Uitvoer:
Exception gevangen: System.DivideByZeroException: Attempted to divide by zero. Resultaat: 0
Gebruiker-gedefinieerde Exceptions
Eigen exception-klassen afleiden van Exception.
Voorbeeld
using System;
namespace GebruikerGedefinieerdeException {
class TestTemperatuur {
static void Main(string[] args) {
Temperatuur temp = new Temperatuur();
try { temp.ToonTemp(); }
catch (TempIsNulException e) { Console.WriteLine("TempIsNulException: {0}", e.Message); }
Console.ReadKey();
}
}
public class TempIsNulException : Exception {
public TempIsNulException(string message) : base(message) { }
}
public class Temperatuur {
int temperatuur = 0;
public void ToonTemp() {
if (temperatuur == 0) throw new TempIsNulException("Nul temperatuur gevonden");
else Console.WriteLine("Temperatuur: {0}", temperatuur);
}
}
}
Uitvoer: TempIsNulException: Nul temperatuur gevonden
Objecten Gooien
Je kunt een object gooien als het direct of indirect van System.Exception afstamt. In catch-blok: throw e; om de huidige exception door te gooien.
C Taal
- PLC vs DCS: de juiste automatiseringssysteem kiezen
- Liebherr PHS Allround: Flexibele, Modulaire Palletverwerking voor Hoog-Capaciteitsproductie
- Liebherr Breidt Palletverwerkingssysteem Uit voor Flexibele Productie
- C# using-statements: imports, aliasen en static directives
- C Bestandsbehandeling: I/O onder de knie krijgen met fopen, fprintf, fread en fseek
- C++ Exception Handling: Praktische Try, Catch, Throw Voorbeelden
- C++ Signaalverwerking onder de knie: Veilige interruptafhandeling en schone programmaterminatie
- Python-exception handling: try, except, else en finally uitgelegd
- Python Exception Handling Onder de Loep: try, except, finally en raise Effectief Gebruiken
- Java Exception Handling meesteren: Try, Catch, Finally, Throw & Throws uitgelegd
- Java 9 Modulesysteem: Verbeteringen, Link-time en Custom Runtime Images