This website collects cookies to deliver better user experience
C# Exception Handling
C# Exception Handling
Handling errors is an important part of programming which makes the program more user-friendly. In this tutorial, we'll learn about how we can handle exceptions in C#.
The throw keyword
The throw keyword is used to throw errors and stops the further execution of a program.
bool authorized =false;if(authorized){// Your business logic here}else{thrownewException("Access denied");}
The throw keyword can be used with many types of exception classes. For example -
if(email ==null){thrownewArgumentNullException("Email cannot be null");}
try-catch
The try-catch statement consist of a try block followed by one or more catch blocks.
try{// Your code blocks}catch(Exception ex){thrownewException("An error occured - "+ ex);}
try-finally
This statement consist of a try block followed by a finally block which runs always after the try block.
try{// Your code here...}finally{// This block will run regardless of the result}
try-catch-finally
This statement consists of a try block followed by one or more catch blocks followed by a finally block which will run always regardless of the result. This is helpful in cases such as you have to free up the memory even if the program doesn't execute successfully.
try{// Your main business logic}catch(Exception ex){thrownewException("Error!");}catch(ArgumentNullException ex){thrownewArgumentNullException("Arg cannot be null");}...// More catch blocks...finally{// It will run regardless of the result}