Handling exceptions (Try / Catch / Finally) in C #
Exception is an issue that appears during program execution. An Exception in C # is a response to an exception situation that occurs while the program is running, for example by dividing by zero.
Exception provides a way to pass control from one part of a program to another. Just like the exception handling in PHP, Exception Handling in C # is built on four keywords: try, catch, finally, and throw .
- try : A try block identifies a block of code where specific exceptions are activated. It is followed by one or more catch blocks.
- catch : A program catches an Exception with an Exception Handler in place in a program where you want to handle that problem. The catch keyword in C # shows how to catch an exception.
- finally : A finally block is used to execute a given set of commands, whether or not an exception is thrown or not thrown. For example, if you open a file, it must be closed, otherwise an exception will be created.
- throw : A program throws an exception when a problem occurs. This is done using the throw keyword in C #.
Syntax
Suppose a block creates an Exeption, a method of catching an exception by using a combination of try and catch keywords. A try / catch block is placed around the code that can create an exception. The code inside a try / catch block is treated as protected code, and the syntax for using try / catch in C # is as follows:
try {
// commands may cause an exception (exception)
} catch (foreign_folder_name e1) {
// code to handle errors
} catch (foreign_folder_name e2) {
// code to handle errors
} catch (foreign_folder_name) {
// code to handle errors
} finally {
// commands to be executed
}
You can list many catch commands to catch different exception types in case your try block appears more than one exception in different situations.
Exception class in C #
Exceptions in C # are represented by classes. The Exception classes in C # are primarily inherited directly or not directly from the System.Exception class in C #. Some Exception classes inherit from the System.Exception class are System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports the exceptions created by application programs. Therefore, the exceptions defined by the programmer should inherit from this class.
The System.SystemException class is the base class for all pre-defined system exception.
The following table provides some classes of pre-defined Exception inherited from the Sytem.SystemException class in C # :
Exception Class DescriptionSystem.IO.IOException Handling error I / O. System.IndexOutOfRangeException Handling errors created when a method references an index outside the array array. System.ArrayTypeMismatchException Handling errors created when type is not suitable for array type. System.NullReferenceException Handling errors created from referencing a null object. System.DivideByZeroException Handling errors created when dividing by 0. System.InvalidCastException Error handling generated during casting. System.OutOfMemoryException Error handling is created from the lack of free memory. System.StackOverflowException Error handling generated from stack overflow.Exception handling (Exception Handling) in C #
C # provides a highly structured solution for exception handling in the form of try and catch blocks. Using these blocks, the main commands of the program are separated from the error handling commands in C #.
These exception handling blocks are implemented by using try, catch and finally keywords in C #. For example, throw an exception when dividing by 0.
using System ; namespace VdXuLyNgoaiLe { class PhepChia { int result ; PhepChia () { result = 0 ; } public void chia ( int so1 , int so2 ) { try { result = so1 / so2 ; } catch (DivideByZeroException e ) { Console . WriteLine ( "Exception caught: {0}" , e ); } finally { Console . WriteLine ( "Kết quả: {0}" , result ); } } static void Main ( string [] args ) { PhepChia d = new PhepChia (); d . chia ( 25 , 0 ); Console . ReadKey (); } } }
When compiling and running the above C # program will produce the following results:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at VdXuLyNgoaiLe.PhepShare.chia (System.Int32 so1, System.Int32 so2) [0x00000] in: 0
Result: 0
Create User-Defined Exception in C #
You can also define exceptions. The User-Defined Exception classes are inherited from the ApplicationException class in C #. The following example illustrates this:
Creating 3 classes named in turn is as follows:
Temperature class
using System ; namespace VdDinhNghiaException { class KtraNhietDo { static void Main ( string [] args ) { NhietDo nhiet = new NhietDo (); try { nhiet . xemNhietDo (); } catch ( TempIsZeroException e ) { Console . WriteLine ( "TempIsZeroException: {0}" , e . Message ); } Console . ReadKey (); } } } public class TempIsZeroException : Exception { public TempIsZeroException ( string message ): base ( message ) { } } public class NhietDo { int temperature = 0 ; public void xemNhietDo () { if ( temperature == 0 ) { throw ( new TempIsZeroException ( "Mức nhiệt độ bằng 0!" )); } else { Console . WriteLine ( "Nhiệt độ: {0}" , temperature ); } } }
Compiling and running the above C # program will produce the following results:
TempIsZeroException: Temperature level is 0!
Throwing Object in C #
You can throw an object if it: either directly or indirectly inherits from the System.Exception class in C #. You can use a throw command in the catch block to throw that presence object:
Catch (Exception e)
{
.
Throw e
}
According to Tutorialspoint
Last lesson: Regular Expression in C #
Next article: File I / O in C #
You should read it
- Exception handling and error (Error & Exception Handling)
- How to fix Unhandled Exception Has Occurred errors on Windows 10
- How to use the Nest.js exception filter for error handling
- How to fix Unexpected Store Exception error in Windows 10
- Fix 'System Thread Exception Not Handled' error on Windows 10
- Instructions for fixing System Service Exception error on Windows
- Error and Exception in Python
- How to fix 0x0000001E: KMODE EXCEPTION NOT HANDLED on Windows
May be interested
- How to add exceptions in Windows Defender on Windows 10windows defender is integrated into windows 10 to find malware. to improve performance for tasks such as compiling code or running virtual machines, you can add exceptions and windows defender will never scan those files.
- How to catch Turkey in Fisch Roblox, Fischgiving eventduring the fischgiving event, you can catch a turkey by fishing in-game. although it sounds strange, it is completely doable. here is a guide on how to catch a turkey in fisch roblox as well as where it appears.
- How to catch Pokemon 'hundred percent hit' in Pokemon Goto be able to catch pokémon quickly and effectively, it is not simply that you will throw pokéball at the pokémon but also need many factors such as adjusting the throwing direction, throwing force, ...
- Fixed IDM does not catch links on Firefox and Chromefix idm error does not catch links on firefox and chrome - currently, internet download manager (idm) - a tool used to download the most used in the world. the regular update of the new version makes idm sometimes fail to catch links
- Conflict handling in Gitjerry is working on the wchar_support branch. he changes the name of the feature and after checking, he repository his changes.
- Summary - How to play Pokemon GO, virtual reality game catch Pokemon on smartphonepokemon go game (styled, raising and training virtual animals) has become popular, the online community with new movements also immediately responded to this mobile game in the direction positive direction
- How to Catch Three Regis in Pokemon Emeraldmany pokémon fans were surprised to realize that the old method of catching pokémon regirock, regice and registeel cannot be used in the emerald version. this article will show you how to unlock them in the pokémon emerald video game. please note that you may need to try multiple times to catch these legendary pokémon.
- Things you didn't know about 26 types of Pokéball - Part 1pokéball is the most important item in pokémon go, allowing gamers to quickly catch pokémon back to their team. the higher the pokéball, the more effective the ability to catch pokémon.
- What color do mosquitoes like? Lamp catch blue or yellow light better?a variety of methods have been developed to limit mosquitoes, including mosquito-catching lamps. so what color do mosquitoes like? lamp catch blue or yellow light better?
- How to catch rare Pokemon in Pokemon GO - Rare creatures, very difficult to catchin the game pokemon go, there are many different types of pokemon, including rare creatures that are very difficult to catch. in the article below, the network administrator will guide you how to catch these rare types of pokemon.