Day 16: Try Statements and Exceptions

Leslie Ramírez
2 min readDec 27, 2021

--

Hello there!! 👋👋👋 It’s our 16th and the last week of coding winter 2021 😲😲😲, the time has passed so fast! It’s been really nice to do this coding calendar and share it with all of you. This time I’m going to share with you a necessary topic. Try-catch statement.

Let’s go!

Try Statements and Exceptions

A try statement specifies a code block subject to error-handling or cleanup code. When an exception occurs, the common language runtime looks for the catch statement that handles the exception. If no catch block is found, then an unhandled exception message is shown stops the execution of the program like this:

The try block must be followed by one or more catch blocks and/or finally block. The catch block executes when an error is thrown in the try block. The finally block executes after the execution leaves the try block. A catch block has access to an Exception object that contains information about the error. A simple way to use it:

General Features

  • Using catch arguments is one way to filter the exceptions you want to handle. You can use an exception filter.
  • It’s possible to have more than one catch clauses in the same try-catch statement. In this case, the catch clauses are examined in order. Another code example with multiple catch clause:
  • Catching System.Exception catches all possible errors. This is useful in the following circumstances:
  • Your program can potentially recover regardless of the specific exception type.
  • You plan to rethrow the exception (perhaps after logging it).
  • Your error handler is the last resort, prior to termination of the program.

Conclusion

The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. A try statement specifies a code block subject to error-handling or cleanup code.

If you enjoyed this article, please hold down the clap button 👏👏👏 Don’t forget to follow our Coding winter Calendar. Have a wonderful day! 🧡 💛 💚🧡 💛 💚

--

--

Leslie Ramírez

I am Microsoft MVP in the award category: Developers technologies, a professional with several years in software development specifically in .NET technology.