ExceptionProgram.cs ← Example Answer Not Included ❗An exception in C# is an error that occurs during program execution when something unexpected happens, like trying to divide by zero or accessing a null reference.
Exceptions are used to handle and manage errors gracefully through try-catch blocks, allowing programs to respond to errors without crashing.
To throw an exception in C#, you use the throw keyword followed by a new instance of an exception class. Here are some examples:
// Kast en standard exception
throw new Exception("Dette er en fejlbesked");
// Kast en specifik exception type
throw new ArgumentNullException("parameterNavn", "Parameter må ikke være null");
// Kast en custom exception
throw new MinCustomException("Min egen fejlbesked");
You can throw exceptions inside a method when certain conditions are met
public void DividerTal(int tal1, int tal2)
{
if (tal2 == 0)
{
throw new DivideByZeroException("Man kan ikke dividere med nul!");
}
int resultat = tal1 / tal2;
}