Industriële fabricage
Industrieel internet der dingen | Industriële materialen | Onderhoud en reparatie van apparatuur | Industriële programmering |
home  MfgRobots >> Industriële fabricage >  >> Industrial programming >> C Taal

C# Exception Handling Beheersen: Strategieën & Best Practices

exception is een probleem dat optreedt tijdens programma-uitvoering. Een C#-exception is een reactie op een uitzonderlijke omstandigheid (bijv. delen door nul).

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. catch markeert 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).

NrException Klasse & Beschrijving
1System.IO.IOException – I/O fouten.
2System.IndexOutOfRangeException – Array index buiten bereik.
3System.ArrayTypeMismatchException – Type mismatch met array.
4System.NullReferenceException – Null object referentie.
5System.DivideByZeroException – Delen door nul.
6System.InvalidCastException – Typecasting fout.
7System.OutOfMemoryException – Onvoldoende geheugen.
8System.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

  1. PLC vs DCS: de juiste automatiseringssysteem kiezen
  2. Liebherr PHS Allround: Flexibele, Modulaire Palletverwerking voor Hoog-Capaciteitsproductie
  3. Liebherr Breidt Palletverwerkingssysteem Uit voor Flexibele Productie
  4. C# using-statements: imports, aliasen en static directives
  5. C Bestandsbehandeling: I/O onder de knie krijgen met fopen, fprintf, fread en fseek
  6. C++ Exception Handling: Praktische Try, Catch, Throw Voorbeelden
  7. C++ Signaalverwerking onder de knie: Veilige interruptafhandeling en schone programmaterminatie
  8. Python-exception handling: try, except, else en finally uitgelegd
  9. Python Exception Handling Onder de Loep: try, except, finally en raise Effectief Gebruiken
  10. Java Exception Handling meesteren: Try, Catch, Finally, Throw & Throws uitgelegd
  11. Java 9 Modulesysteem: Verbeteringen, Link-time en Custom Runtime Images