Table of Contents

Exception

C# and the .NET CLR use exceptions to show that an error condition has arisen during program execution. C# programs are under constant threat of running into some sort of problem. As a program’s complexity grows, the probability that something odd would happen during its execution also gets higher.

In this blog, we will go through the basics of Exception and Exception handling. We will also look at how we can achieve exception handling using try, catch, and finally blocks and how to create your own custom exceptions.

Exception

The errors which we are getting at the run time of the application is called an exception.

If any exception is coming into our application then the application is abnormally terminated. The Application is not considered as a good application if any exception is coming and it is not handled.

Every time when we are developing an application and it got successfully build without any errors. Then this happens

Exception

For that, it is good practice to use exception handling.

Common .NET Exceptions :

Below are the common .NET exceptions which we can see on a regular basis of coding.

System.NullReferenceException – Occurs when calling a method on a null object reference

System.IndexOutOfRangeException – Occurs attempting to access an array element that does not exist

System.IO.IOException – Used around many file I/O type operations

System.OutOfMemoryException – Occurs when the app runs out of memory

System.InvalidCastException – Occurs when you try to cast an object to a type that it can’t be cast to

System.InvalidOperationException - Occurs when a method call is invalid for the object's current state

System.ArgumentException - Occurs when one of the arguments provided to a method is not valid

Exception Handling

The process of handling any run time error is called exception handling. The exception handling is performed to maintain the normal flow of the application.

In C# we can achieve this using the below techniques:

Try,Catch & Finally blocks

This is a very basic Exception handling technique in which try, catch, and finally, blocks are used.

try block: In this block the code is written which may cause the exception. If any exception is thrown then the corresponding catch block is executed.

catch block: In this block the exception is caught which means if an exception is thrown from the try block then we write the code to handle or log it.

finally block: In this block we write the certain code which we want to execute if an exception is thrown or not. For example: disposing of an object or closing the database connection.

Exception Handling after using try, catch blocks

Exception Handling

Note: Multiple finally blocks are not allowed. Also, the finally block cannot have the return, continue, or break keywords. It doesn't let control leave the finally block.

In C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. The try block without a catch or finally block will give a compile-time error.

If there is no exception occurred inside the try block, the control directly transfers to the finally block. We can say that the statements inside the finally block are executed always.

Multiple Catch blocks

We can use the multiple catch blocks when we are not sure which type of exception will be thrown by the code. So that will help to catch the multiple types of exceptions.

Catch multiple exceptions in the single catch block

We can use the generic exception class as well to catch all types of exception in that case we have to write the catch block as below:

Note: Multiple catch blocks with the same exception type are not allowed. A catch block with the base Exception type must be the last block.

Exception Filters

In C# 6.0 a new feature is introduced to handle the exception which is called the Exception Filters. This feature will allow you to handle more specific exceptions in catch blocks so that you can write the code specific to the exception condition.

Like before C# 6.0 We had to catch any exception and handle it. Now in C# 6.0, we can handle the exception specific to the condition.

Nested try-catch

C# allows nested try-catch blocks. When using nested try-catch blocks, an exception will be caught in the first matching catch block that follows the try block where an exception occurred.

An inner catch block will be executed in the above example because it is the first catch block that handles all exception types.

If there is not an inner catch block that matches with raised exception type, then the control will flow to the outer catch block until it finds an appropriate exception filter.

Throw an Exception

C# allows throwing an exception. The keyword is used for that purpose. One of the benefits of throwing an exception can be when a problem occurs in the middle of the complicated method execution because handling that situation in that complicated method would make that method even more complex. Then we should throw an exception and let the catch block to handle it.

The throw keyword can only be used with the Exception object except for the catch block. It will be discussed in the next section.

Note: The throw keyword is used to throw or create the new exception. If the throw keyword is used and if there is any catch block then the catch block will be executed next.

Rethrow an Exception

When an exception is caught in the catch block, we can do some operations and then re-throw the exception. Rethrow an exception means calling the keyword without an exception object inside a catch block.

Here is the point to note that if we follow the below approach to rethrow the exception then the proper stack trace will not be maintained means it will not point out that actually where the exception occurred it will show in the stack trace the line number from which the exception is rethrown.

Now if we follow the below approach then the proper stack trace will be maintained with maintaining the exact line number where the exception actually occurred.

User-defined Exceptions

User-defined exceptions are those exceptions that are not defined by the programming language. In C# we can create our own custom exceptions(User-defined exceptions)

C# exceptions are defined as classes, just like any other C# object. All exceptions are inherited from a base System.Exception class. There are many common exceptions that you can use within your own code.

Creating your own C# custom exceptions is helpful only when you are going to catch that specific type of exception and handle it differently.

Exception Handling Best Practices

Log Exception

It is considered a good practice to log all the exception which are coming into our application. The main benefit of logging exceptions that we can know exactly what are the conditions on which the code is failing instead of asking from the user that what inputs he has provided we can log all the required information and use that data to solve the error.

In many cases, we just ignore the catch block by writing nothing in it. There are some .NET libraries available for logging purposes like NLog, Serilog, etc.

We can log exception into the catch block. Every exception is coming into our application is crucial as they are critical to finding the problems in the code.

First Chance & Second Chance Exception

The first chance exception is mainly designed for debugging purposes. Like whenever an exception occurs it first goes to the debugger giving the first chance to you and then to the program/application. If that exception is unhandled in the program/application then it gets back to the debugger giving a second chance to you to do something with your code before and after the application itself decides to do.

It gives you visibility into every .NET exception being thrown.

We can enable the first chance exception in the Visual Studio by going into the Debug > Windows > Exception Settings > check next to "Common Language Runtime Exceptions"

You can also select the exceptions you want the debugger to break automatically in the above setting.

Conclusion

In this blog, we learned about the basics of Exception, Exception Handling, and some best practices of exception handling. Use of the exception handling with its best practices in the application will help the application to run smoother and without any bad user experience.

Hemant Manwani
By Hemant ManwaniHemant Manwani is a Software Engineer at LoginRadius who is interested in how the web works and developer tools that make working with web easier.
Featured Posts

TOTP Authentication Explained: How It Works, Why It’s Secure

Advantages of Time-Based One-Time Passwords (TOTP)

JWT Authentication with LoginRadius: Quick Integration Guide

Complete Guide to JSON Web Token (JWT) and How It Works

A comprehensive guide to OAuth 2.0

How Chrome’s Third-Party Cookie Restrictions Affect User Authentication?

How to Implement OpenID Connect (OIDC) SSO with LoginRadius?

Testing Brute-force Lockout with LoginRadius

Breaking Down the Decision: Why We Chose AWS ElastiCache Over Redis Cloud

LoginRadius Launches a CLI for Enterprise Dashboard

How to Implement JWT Authentication for CRUD APIs in Deno

Multi-Factor Authentication (MFA) with Redis Cache and OTP

Introduction to SolidJS

Why We Re-engineered LoginRadius APIs with Go?

Why B2B Companies Should Implement Identity Management

Top 10 Cyber Threats in 2022

Build a Modern Login/Signup Form with Tailwind CSS and React

M2M Authorization: Authenticate Apps, APIs, and Web Services

Implement HTTP Streaming with Node.js and Fetch API

NestJS: How to Implement Session-Based User Authentication

How to Integrate Invisible reCAPTCHA for Bot Protection

How Lapsus$ Breached Okta and What Organizations Should Learn

NestJS User Authentication with LoginRadius API

How to Authenticate Svelte Apps

How to Build Your Github Profile

Why Implement Search Functionality for Your Websites

Flutter Authentication: Implementing User Signup and Login

How to Secure Your LoopBack REST API with JWT Authentication

When Can Developers Get Rid of Password-based Authentication?

4 Ways to Extend CIAM Capabilities of BigCommerce

Node.js User Authentication Guide

Your Ultimate Guide to Next.js Authentication

Local Storage vs. Session Storage vs. Cookies

How to Secure a PHP API Using JWT

React Security Vulnerabilities and How to Fix/Prevent Them

Cookie-based vs. Cookieless Authentication: What’s the Future?

Using JWT Flask JWT Authentication- A Quick Guide

Single-Tenant vs. Multi-Tenant: Which SaaS Architecture is better for Your Business?

Build Your First Smart Contract with Ethereum & Solidity

What are JWT, JWS, JWE, JWK, and JWA?

How to Build an OpenCV Web App with Streamlit

32 React Best Practices That Every Programmer Should Follow

How to Build a Progressive Web App (PWA) with React

Bootstrap 4 vs. Bootstrap 5: What is the Difference?

JWT Authentication — Best Practices and When to Use

What Are Refresh Tokens? When & How to Use Them

How to Participate in Hacktoberfest as a Maintainer

How to Upgrade Your Vim Skills

Hacktoberfest 2021: Contribute and Win Swag from LoginRadius

How to Implement Role-Based Authentication with React Apps

How to Authenticate Users: JWT vs. Session

How to Use Azure Key Vault With an Azure Web App in C#

How to Implement Registration and Authentication in Django?

11 Tips for Managing Remote Software Engineering Teams

One Vision, Many Paths: How We’re Supporting freeCodeCamp

C# Init-Only Setters Property

Content Security Policy (CSP)

Implementing User Authentication in a Python Application

Introducing LoginRadius CLI

Add Authentication to Play Framework With OIDC and LoginRadius

React renderers, react everywhere?

React's Context API Guide with Example

Implementing Authentication on Vue.js using JWTtoken

How to create and use the Dictionary in C#

What is Risk-Based Authentication? And Why Should You Implement It?

React Error Boundaries

Data Masking In Nginx Logs For User Data Privacy And Compliance

Code spliting in React via lazy and suspense

Implement Authentication in React Applications using LoginRadius CLI

What is recoil.js and how it is managing in react?

How Enum.TryParse() works in C#

React with Ref

Implement Authentication in Angular 2+ application using LoginRadius CLI in 5 mins

How Git Local Repository Works

How to add SSO for your WordPress Site!

Guide to Authorization Code Flow for OAuth 2.0

Introduction to UniFi Ubiquiti Network

The Upcoming Future of Software Testers and SDETs in 2021

Why You Need an Effective Cloud Management Platform

What is Adaptive Authentication or Risk-based Authentication?

Top 9 Challenges Faced by Every QA

Top 4 Serverless Computing Platforms in 2021

QA Testing Process: How to Deliver Quality Software

How to Create List in C#

What is a DDoS Attack and How to Mitigate it

How to Verify Email Addresses in Google Sheet

Concurrency vs Parallelism: What's the Difference?

35+ Git Commands List Every Programmer Should Know

How to do Full-Text Search in MongoDB

What is API Testing? - Discover the Benefits

The Importance of Multi-Factor Authentication (MFA)

Optimize Your Sign Up Page By Going Passwordless

Image Colorizer Tool - Kolorizer

PWA vs Native App: Which one is Better for you?

How to Deploy a REST API in Kubernetes

Integration with electronic identity (eID)

How to Work with Nullable Types in C#

Git merge vs. Git Rebase: What's the difference?

How to Install and Configure Istio

How to Perform Basic Query Operations in MongoDB

Invalidating JSON Web Tokens

How to Use the HTTP Client in GO To Enhance Performance

Constructor vs getInitialState in React

Web Workers in JS - An Introductory Guide

How to Use Enum in C#

How to Migrate Data In MongoDB

A Guide To React User Authentication with LoginRadius

WebAuthn: A Guide To Authenticate Your Application

Build and Push Docker Images with Go

Istio Service Mesh: A Beginners Guide

How to Perform a Git Force Pull

NodeJS Server using Core HTTP Module

How does bitwise ^ (XOR) work?

Introduction to Redux Saga

React Router Basics: Routing in a Single-page Application

How to send emails in C#/.NET using SMTP

How to create an EC2 Instance in AWS

How to use Git Cherry Pick

Password Security Best Practices & Compliance

Using PGP Encryption with Nodejs

Python basics in minutes

Automating Rest API's using Cucumber and Java

Bluetooth Controlled Arduino Car Miniature

AWS Services-Walkthrough

Beginners Guide to Tweepy

Introduction to Github APIs

Introduction to Android Studio

Login Screen - Tips and Ideas for Testing

Introduction to JAMstack

A Quick Look at the React Speech Recognition Hook

IoT and AI - The Perfect Match

A Simple CSS3 Accordion Tutorial

EternalBlue: A retrospective on one of the biggest Windows exploits ever

Setup a blog in minutes with Jekyll & Github

What is Kubernetes? - A Basic Guide

Why RPA is important for businesses

Best Hacking Tools

Three Ways to do CRUD Operations On Redis

Traversing the realms of Quantum Network

How to make a telegram bot

iOS App Development: How To Make Your First App

Apache Beam: A Basic Guide

Python Virtual Environment: What is it and how it works?

End-to-End Testing with Jest and Puppeteer

Speed Up Python Code

Build A Twitter Bot Using NodeJS

Visualizing Data using Leaflet and Netlify

STL Containers & Data Structures in C++

Secure Enclave in iOS App

Optimal clusters for KMeans Algorithm

Upload files using NodeJS + Multer

Class Activation Mapping in Deep Learning

Full data science pipeline implementation

HTML Email Concept

Blockchain: The new technology of trust

Vim: What is it and Why to use it?

Virtual Dispersive Networking

React Context API: What is it and How it works?

Breaking down the 'this' keyword in Javascript

Handling the Cheapest Fuel- Data

GitHub CLI Tool ⚒

Lazy loading in React

What is GraphQL? - A Basic Guide

Exceptions and Exception Handling in C#

Unit Testing: What is it and why do you need it?

Golang Maps - A Beginner’s Guide

LoginRadius Open Source For Hacktoberfest 2020

JWT Signing Algorithms

How to Render React with optimization

Ajax and XHR using plain JS

Using MongoDB as Datasource in GoLang

Understanding event loop in JavaScript

LoginRadius Supports Hacktoberfest 2020

How to implement Facebook Login

Production Grade Development using Docker-Compose

Web Workers: How to add multi-threading in JS

Angular State Management With NGXS

What's new in the go 1.15

Let’s Take A MEME Break!!!

PKCE: What it is and how to use it with OAuth 2.0

Big Data - Testing Strategy

Email Verification API (EVA)

Implement AntiXssMiddleware in .NET Core Web

Setting Up and Running Apache Kafka on Windows OS

Getting Started with OAuth 2.0

Best Practice Guide For Rest API Security | LoginRadius

Let's Write a JavaScript Library in ES6 using Webpack and Babel

Cross Domain Security

Best Free UI/UX Design Tools/Resources 2020

A journey from Node to GoLang

React Hooks: A Beginners Guide

DESIGN THINKING -A visual approach to understand user’s needs

Deep Dive into Container Security Scanning

Different ways to send an email with Golang

Snapshot testing using Nightwatch and mocha

Qualities of an agile development team

IAM, CIAM, and IDaaS - know the difference and terms used for them

How to obtain iOS application logs without Mac

Benefits and usages of Hosts File

React state management: What is it and why to use it?

HTTP Security Headers

Sonarqube: What it is and why to use it?

How to create and validate JSON Web Tokens in Deno

Cloud Cost Optimization in 2021

Service Mesh with Envoy

Kafka Streams: A stream processing guide

Self-Hosted MongoDB

Roadmap of idx-auto-tester

How to Build a PWA in Vanilla JS

Password hashing with NodeJS

Introduction of Idx-Auto-Tester

Twitter authentication with Go Language and Goth

Google OAuth2 Authentication in Golang

LinkedIn Login using Node JS and passport

Read and Write in a local file with Deno

Build A Simple CLI Tool using Deno

Create REST API using deno

Automation for Identity Experience Framework is now open-source !!!

Creating a Web Application using Deno

Hello world with Deno

Facebook authentication using NodeJS and PassportJS

StackExchange - The 8 best resources every developer must follow

OAuth implementation with Node.js and Github

NodeJS and MongoDB application authentication by JWT

Working with AWS Lambda and SQS

Google OAuth2 Authentication in NodeJS - A Guide to Implementing OAuth in Node.js

Custom Encoders in the Mongo Go Driver

React's Reconciliation Algorithm

NaN in JavaScript: An Essential Guide

SDK Version 10.0.0

Getting Started with gRPC - Part 1 Concepts

Introduction to Cross-Site Request Forgery (CSRF)

Introduction to Web Accessibility with Semantic HTML5

JavaScript Events: Bubbling, Capturing, and Propagation

3 Simple Ways to Secure Your Websites/Applications

Failover Systems and LoginRadius' 99.99% Uptime

A Bot Protection Overview

OAuth 1.0 VS OAuth 2.0

Azure AD as an Identity provider

How to Use JWT with OAuth

Let's Encrypt with SSL Certificates

Encryption and Hashing

What is JSON Web Token

Understanding JSONP

Using NuGet to publish .NET packages

How to configure the 'Actions on Google' console for Google Assistant

Creating a Google Hangout Bot with Express and Node.js

EOL or End of Line or newline ascii character

Cocoapods : What It Is And How To Install?

Node Package Manager (NPM)

Get your FREE SSL Certificate!

jCenter Dependencies in Android Studio

Maven Dependency in Eclipse

Install Bootstrap with Bower

Open Source Business Email Validator By Loginradius

Know The Types of Website Popups and How to Create Them

Javascript tips and tricks to Optimize Performance

Learn How To Code Using The 10 Cool Websites

Personal Branding For Developers: Why and How?

Wordpress Custom Login Form Part 1

Is Your Database Secured? Think Again

Be More Manipulative with Underscore JS

Extended LinkedIn API Usage

Angular Roster Tutorial

How to Promise

Learning How to Code

Delete a Node, Is Same Tree, Move Zeroes

CSS/HTML Animated Dropdown Navigation

Part 2 - Creating a Custom Login Form

Website Authentication Protocols

Nim Game, Add Digits, Maximum Depth of Binary Tree

The truth about CSS preprocessors and how they can help you

Beginner's Guide for Sublime Text 3 Plugins

Displaying the LoginRadius interface in a pop-up

Optimize jQuery & Sizzle Element Selector

Maintain Test Cases in Excel Sheets

Separate Drupal Login Page for Admin and User

How to Get Email Alerts for Unhandled PHP Exceptions

ElasticSearch Analyzers for Emails

Social Media Solutions

Types of Authentication in Asp.Net

Using Facebook Graph API After Login

Hi, My Name is Darryl, and This is How I Work

Beginner's Guide for Sublime Text 3

Social Network Branding Guidelines

Index in MongoDB

How to ab-USE CSS2 sibling selectors

Customize User Login, Register and Forgot Password Page in Drupal 7

Best practice for reviewing QQ app

CSS3 Responsive Icons

Write a highly efficient python Web Crawler

Memcached Memory Management

HTML5 Limitation in Internet Explorer

What is an API

Styling Radio and Check buttons with CSS

Configuring Your Social Sharing Buttons

Shopify Embedded App

API Debugging Tools

Use PHP to generate filter portfolio

Password Security

Loading spinner using CSS

RDBMS vs NoSQL

Cloud storage vs Traditional storage

Getting Started with Phonegap

Animate the modal popup using CSS

CSS Responsive Grid, Re-imagined

An Intro to Curl & Fsockopen

Enqueuing Scripts in WordPress

How to Implement Facebook Social Login

GUID Query Through Mongo Shell

Integrating LinkedIn Social Login on a Website

Social Provider Social Sharing Troubleshooting Resources

Social Media Colors in Hex

W3C Validation: What is it and why to use it?

A Simple Popup Tutorial

Hello developers and designers!

Share On:
Share on TwitterShare on LinkedIn