What Are Try-Catch Statements?
Well-designed applications include error handling to capture unplanned issues. Many programming languages, including Java, JavaScript, ColdFusion and Microsoft SQL, use try-catch statements for error handling. A try-catch statement encapsulates a section of code and provides specific results for any errors that occur when the code executes.
-
Error Handling
-
Error handling in an application can capture specific errors or error categories. Programmers can display specific error messages, trigger alerts to administrators, record errors in a database, and trigger additional actions based on the error that occurs. Without error handling in place, you run the risk of having unpredictable results occur within your application when an error occurs.
Try Statements
-
The "try" portion of a try-catch statement contains the code to be executed. This is the regular code that the programmer believes might cause an error. This could include checking for a blank or invalid form input in an insert statement, verifying that math statements don't contain division by zero, or any other behavior that might lead to undesirable results.
-
Catch Statements
-
The "catch" statement is the portion of the statement that captures the error and triggers additional actions as a result. A catch statement can capture a very specific situation, such as division by zero, or can capture broad classes of errors. Inside the catch statement, you can program specific actions to occur, such as transaction rollbacks or display of error messages.
Syntax
-
The syntax of a try-catch block varies slightly depending on the language. In all cases, though, there is an opening "try" statement that tells the application it is entering a try-catch block. Within that block, there is some segment of code, followed by a catch statement. Most languages support multiple catch statements, which generally use an opening tag and a closing tag to indicate their start and stop. Catch statements should be the last item inside a try block.
-