When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).
There are two types of exceptions
a. System generated Exceptions
b. Custom Exception
Common System Exceptions
Here are some common system exceptions:
Key Concepts of Exception Handling
Syntax
try
{
// Code that might throw an exception
}
catch (ExceptionType1 ex)
{
// Code to handle ExceptionType1
}
catch (ExceptionType2 ex)
{
// Code to handle ExceptionType2
}
finally
{
// Code that always executes
}
Example 1: Handling a Specific Exception
using System;
public class Example
{
public static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index was outside the bounds of the array.");
Console.WriteLine($"Exception Message: {ex.Message}");
}
finally
{
Console.WriteLine("Execution of the try-catch block is complete.");
}
}
}
Example 2: Catching Multiple Exceptions
using System;
using System.IO;
public class Example
{
public static void Main()
{
try
{
int result = 10 / int.Parse("0"); // Will cause DivideByZeroException
string content = File.ReadAllText("nonexistentfile.txt"); // Will cause FileNotFoundException
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
Console.WriteLine($"Exception Message: {ex.Message}");
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found.");
Console.WriteLine($"Exception Message: {ex.Message}");
}
catch (Exception ex)
{
// General catch block for any other exceptions
Console.WriteLine("An error occurred.");
Console.WriteLine($"Exception Message: {ex.Message}");
}
finally
{
Console.WriteLine("Execution of the try-catch block is complete.");
}
}
}
Example 3: Throwing Exceptions
You can explicitly throw exceptions using the throw keyword.
using System;
public class Example
{
public static void Main()
{
try
{
ValidateNumber(-1);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
static void ValidateNumber(int number)
{
if (number < 0)
{
throw new ArgumentException("Number cannot be negative.");
}
}
}
Custom Exceptions
You can create your own custom exception classes by inheriting from the Exception class.
using System;
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
public class Example
{
public static void Main()
{
try
{
throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
Console.WriteLine($"Caught a custom exception: {ex.Message}");
}
}
}
Best Practices
Catch Specific Exceptions: Always catch specific exceptions rather than using a general catch block. This helps in understanding the exact issue and handling it accordingly.
Use Finally for Cleanup: Use the finally block to release resources or perform cleanup activities.
Avoid Silent Catch Blocks: Do not catch exceptions without handling them. At least log the exception details.
Custom Exceptions for Domain-Specific Errors: Use custom exceptions to represent domain-specific errors, which makes the code more readable and maintainable.
When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).
There are two types of exceptions
a. System generated Exceptions
b. Custom Exception
Common System Exceptions
Here are some common system exceptions:
Key Concepts of Exception Handling
Syntax
try { // Code that might throw an exception } catch (ExceptionType1 ex) { // Code to handle ExceptionType1 } catch (ExceptionType2 ex) { // Code to handle ExceptionType2 } finally { // Code that always executes }
Example 1: Handling a Specific Exception
using System; public class Example { public static void Main() { try { int[] numbers = { 1, 2, 3 }; Console.WriteLine(numbers[5]); } catch (IndexOutOfRangeException ex) { Console.WriteLine("Index was outside the bounds of the array."); Console.WriteLine($"Exception Message: {ex.Message}"); } finally { Console.WriteLine("Execution of the try-catch block is complete."); } } }
Example 2: Catching Multiple Exceptions
using System; using System.IO; public class Example { public static void Main() { try { int result = 10 / int.Parse("0"); // Will cause DivideByZeroException string content = File.ReadAllText("nonexistentfile.txt"); // Will cause FileNotFoundException } catch (DivideByZeroException ex) { Console.WriteLine("Cannot divide by zero."); Console.WriteLine($"Exception Message: {ex.Message}"); } catch (FileNotFoundException ex) { Console.WriteLine("File not found."); Console.WriteLine($"Exception Message: {ex.Message}"); } catch (Exception ex) { // General catch block for any other exceptions Console.WriteLine("An error occurred."); Console.WriteLine($"Exception Message: {ex.Message}"); } finally { Console.WriteLine("Execution of the try-catch block is complete."); } } }
Example 3: Throwing Exceptions
You can explicitly throw exceptions using the throw keyword.
using System; public class Example { public static void Main() { try { ValidateNumber(-1); } catch (ArgumentException ex) { Console.WriteLine($"Exception: {ex.Message}"); } } static void ValidateNumber(int number) { if (number < 0) { throw new ArgumentException("Number cannot be negative."); } } }
Custom Exceptions
You can create your own custom exception classes by inheriting from the Exception class.
using System; public class CustomException : Exception { public CustomException(string message) : base(message) { } } public class Example { public static void Main() { try { throw new CustomException("This is a custom exception."); } catch (CustomException ex) { Console.WriteLine($"Caught a custom exception: {ex.Message}"); } } }
Best Practices
Catch Specific Exceptions: Always catch specific exceptions rather than using a general catch block. This helps in understanding the exact issue and handling it accordingly.
Use Finally for Cleanup: Use the finally block to release resources or perform cleanup activities.
Avoid Silent Catch Blocks: Do not catch exceptions without handling them. At least log the exception details.
Custom Exceptions for Domain-Specific Errors: Use custom exceptions to represent domain-specific errors, which makes the code more readable and maintainable.
C# is primarily used on the Windows . NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved