Try catch exception handling

Catching and Handling Exceptions

This section describes how to use the three exception handler components — the try , catch , and finally blocks — to write an exception handler. Then, the try- with-resources statement, introduced in Java SE 7, is explained. The try- with-resources statement is particularly suited to situations that use Closeable resources, such as streams.

The last part of this section walks through an example and analyzes what occurs during various scenarios.

The following example defines and implements a class named ListOfNumbers . When constructed, ListOfNumbers creates an ArrayList that contains 10 Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList , which writes the list of numbers into a text file called OutFile.txt . This example uses output classes defined in java.io , which are covered in Basic I/O.

The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an IOException . The second boldface line is a call to the ArrayList class’s get method, which throws an IndexOutOfBoundsException if the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by the ArrayList ).

If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor. However, it does not display an error message about the exception thrown by get . The reason is that the exception thrown by the constructor, IOException , is a checked exception, and the one thrown by the get method, IndexOutOfBoundsException , is an unchecked exception.

Now that you’re familiar with the ListOfNumbers class and where the exceptions can be thrown within it, you’re ready to write exception handlers to catch and handle those exceptions.

Источник

try. catch

The try. catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.

Try it

Syntax

The statements to be executed.

Statement that is executed if an exception is thrown in the try -block.

An optional identifier to hold the caught exception for the associated catch block. If the catch block does not utilize the exception’s value, you can omit the exceptionVar and its surrounding parentheses, as catch <. >.

Statements that are executed before control flow exits the try. catch. finally construct. These statements execute regardless of whether an exception was thrown or caught.

Description

The try statement always starts with a try block. Then, a catch block or a finally block must be present. It’s also possible to have both catch and finally blocks. This gives us three forms for the try statement:

  • try. catch
  • try. finally
  • try. catch. finally

Unlike other constructs such as if or for , the try , catch , and finally blocks must be blocks, instead of single statements.

A catch -block contains statements that specify what to do if an exception is thrown in the try -block. If any statement within the try -block (or in a function called from within the try -block) throws an exception, control is immediately shifted to the catch -block. If no exception is thrown in the try -block, the catch -block is skipped.

The finally block will always execute before control flow exits the try. catch. finally construct. It always executes, regardless of whether an exception was thrown or caught.

You can nest one or more try statements. If an inner try statement does not have a catch -block, the enclosing try statement’s catch -block is used instead.

You can also use the try statement to handle JavaScript exceptions. See the JavaScript Guide for more information on JavaScript exceptions.

Unconditional catch-block

When a catch -block is used, the catch -block is executed when any exception is thrown from within the try -block. For example, when the exception occurs in the following code, control transfers to the catch -block.

The catch -block specifies an identifier ( e in the example above) that holds the value of the exception; this value is only available in the scope of the catch -block.

Conditional catch-blocks

You can create «Conditional catch -blocks» by combining try. catch blocks with if. else if. else structures, like this:

A common use case for this is to only catch (and silence) a small subset of expected errors, and then re-throw the error in other cases:

The exception identifier

When an exception is thrown in the try -block, exception_var (i.e., the e in catch (e) ) holds the exception value. You can use this identifier to get information about the exception that was thrown. This identifier is only available in the catch -block’s scope. If you don’t need the exception value, it could be omitted.

The finally-block

The finally block contains statements to execute after the try block and catch block(s) execute, but before the statements following the try. catch. finally block. Control flow will always enter the finally block, which can proceed in one of the following ways:

  • Immediately before the try block finishes execution normally (and no exceptions were thrown);
  • Immediately before the catch block finishes execution normally;
  • Immediately before a control-flow statement ( return , throw , break , continue ) is executed in the try block or catch block.
Читайте также:  Sign up error messages

If an exception is thrown from the try block, even when there’s no catch block to handle the exception, the finally block still executes, in which case the exception is still thrown immediately after the finally block finishes executing.

The following example shows one use case for the finally -block. The code opens a file and then executes statements that use the file; the finally -block makes sure the file always closes after it is used even if an exception was thrown.

Control flow statements ( return , throw , break , continue ) in the finally block will «mask» any completion value of the try block or catch block. In this example, the try block tries to return 1, but before returning, the control flow is yielded to the finally block first, so the finally block’s return value is returned instead.

It is generally a bad idea to have control flow statements in the finally block. Only use it for cleanup code.

Examples

Nested try-blocks

First, let’s see what happens with this:

Now, if we already caught the exception in the inner try -block by adding a catch -block:

And now, let’s rethrow the error.

Any given exception will be caught only once by the nearest enclosing catch -block unless it is rethrown. Of course, any new exceptions raised in the «inner» block (because the code in catch -block may do something that throws), will be caught by the «outer» block.

Returning from a finally-block

If the finally -block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch -blocks. This includes exceptions thrown inside of the catch -block:

The outer «oops» is not thrown because of the return in the finally -block. The same would apply to any value returned from the catch -block.

Источник

Exception Handling (C# Programming Guide)

A try block is used by C# programmers to partition code that might be affected by an exception. Associated catch blocks are used to handle any resulting exceptions. A finally block contains code that is run whether or not an exception is thrown in the try block, such as releasing resources that are allocated in the try block. A try block requires one or more associated catch blocks, or a finally block, or both.

The following examples show a try-catch statement, a try-finally statement, and a try-catch-finally statement.

A try block without a catch or finally block causes a compiler error.

Catch Blocks

A catch block can specify the type of exception to catch. The type specification is called an exception filter. The exception type should be derived from Exception. In general, don’t specify Exception as the exception filter unless either you know how to handle all exceptions that might be thrown in the try block, or you’ve included a throw statement at the end of your catch block.

Multiple catch blocks with different exception classes can be chained together. The catch blocks are evaluated from top to bottom in your code, but only one catch block is executed for each exception that is thrown. The first catch block that specifies the exact type or a base class of the thrown exception is executed. If no catch block specifies a matching exception class, a catch block that doesn’t have any type is selected, if one is present in the statement. It’s important to position catch blocks with the most specific (that is, the most derived) exception classes first.

Catch exceptions when the following conditions are true:

  • You have a good understanding of why the exception might be thrown, and you can implement a specific recovery, such as prompting the user to enter a new file name when you catch a FileNotFoundException object.
  • You can create and throw a new, more specific exception.
  • You want to partially handle an exception before passing it on for more handling. In the following example, a catch block is used to add an entry to an error log before rethrowing the exception.

You can also specify exception filters to add a boolean expression to a catch clause. Exception filters indicate that a specific catch clause matches only when that condition is true. In the following example, both catch clauses use the same exception class, but an extra condition is checked to create a different error message:

An exception filter that always returns false can be used to examine all exceptions but not process them. A typical use is to log exceptions:

The LogException method always returns false , no catch clause using this exception filter matches. The catch clause can be general, using System.Exception, and later clauses can process more specific exception classes.

Finally Blocks

A finally block enables you to clean up actions that are performed in a try block. If present, the finally block executes last, after the try block and any matched catch block. A finally block always runs, whether an exception is thrown or a catch block matching the exception type is found.

The finally block can be used to release resources such as file streams, database connections, and graphics handles without waiting for the garbage collector in the runtime to finalize the objects. For more information See the using Statement.

In the following example, the finally block is used to close a file that is opened in the try block. Notice that the state of the file handle is checked before the file is closed. If the try block can’t open the file, the file handle still has the value null and the finally block doesn’t try to close it. Instead, if the file is opened successfully in the try block, the finally block closes the open file.

Читайте также:  Kivi 50ur50gr инструкция по прошивке

C# Language Specification

For more information, see Exceptions and The try statement in the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Источник

Java Exceptions — Try. Catch

Java Exceptions

When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

The output will be something like this:

If an error occurs, we can use try. catch to catch the error and execute some code to handle it:

Example

The output will be:

Finally

The finally statement lets you execute code, after try. catch , regardless of the result:

Example

The output will be:

Many Exceptions

You can define as many catch blocks as you want:

Syntax

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException , FileNotFoundException , ArrayIndexOutOfBoundsException , SecurityException , etc:

Example

Throw an exception if age is below 18 (print «Access denied»). If age is 18 or older, print «Access granted»:

The output will be:

If age was 20, you would not get an exception:

Источник

Control flow and error handling

JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.

The JavaScript reference contains exhaustive details about the statements in this chapter. The semicolon ( ; ) character is used to separate statements in JavaScript code.

Any JavaScript expression is also a statement. See Expressions and operators for complete information about expressions.

Block statement

The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly brackets:

Example

Block statements are commonly used with control flow statements ( if , for , while ).

Here, < x++; >is the block statement.

Note: var -declared variables are not block-scoped, but are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:

This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. (In C or Java, the equivalent code would have output 1 .)

This scoping effect can be mitigated by using let or const .

Conditional statements

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if. else and switch .

if. else statement

Use the if statement to execute a statement if a logical condition is true . Use the optional else clause to execute a statement if the condition is false .

An if statement looks like this:

Here, the condition can be any expression that evaluates to true or false . (See Boolean for an explanation of what evaluates to true and false .)

If condition evaluates to true , statement_1 is executed. Otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You can also compound the statements using else if to have multiple conditions tested in sequence, as follows:

In the case of multiple conditions, only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ( < /* … */ >).

Best practice

In general, it’s good practice to always use block statements—especially when nesting if statements:

In general it’s good practice to not have an if. else with an assignment like x = y as a condition:

However, in the rare case you find yourself wanting to do something like that, the while documentation has a Using an assignment as a condition section with guidance on a general best-practice syntax you should know about and follow.

Falsy values

The following values evaluate to false (also known as Falsy values):

All other values—including all objects—evaluate to true when passed to a conditional statement.

Note: Do not confuse the primitive boolean values true and false with the true and false values of the Boolean object!

Example

In the following example, the function checkData returns true if the number of characters in a Text object is three. Otherwise, it displays an alert and returns false .

switch statement

A switch statement allows a program to evaluate an expression and attempt to match the expression’s value to a case label. If a match is found, the program executes the associated statement.

A switch statement looks like this:

JavaScript evaluates the above switch statement as follows:

  • The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements.
  • If no matching label is found, the program looks for the optional default clause:
    • If a default clause is found, the program transfers control to that clause, executing the associated statements.
    • If no default clause is found, the program resumes execution at the statement following the end of switch .
    • (By convention, the default clause is written as the last clause, but it does not need to be so.)
Читайте также:  Explay you tv прошивка

break statements

The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed, and then continues execution at the statement following switch . If break is omitted, the program continues execution inside the switch statement (and will evaluate the next case , and so on).

Example

In the following example, if fruitType evaluates to ‘Bananas’ , the program matches the value with case ‘Bananas’ and executes the associated statement. When break is encountered, the program exits the switch and continues execution from the statement following switch . If break were omitted, the statement for case ‘Cherries’ would also be executed.

Exception handling statements

You can throw exceptions using the throw statement and handle them using the try. catch statements.

Exception types

Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is common to throw numbers or strings as errors, it is frequently more effective to use one of the exception types specifically created for this purpose:

throw statement

Use the throw statement to throw an exception. A throw statement specifies the value to be thrown:

You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:

try. catch statement

The try. catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try. catch statement catches it.

The try. catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block.

In other words, you want the try block to succeed—but if it does not, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try. catch statement.

The following example uses a try. catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number ( 1 – 12 ), an exception is thrown with the value ‘InvalidMonthNo’ and the statements in the catch block set the monthName variable to ‘unknown’ .

The catch block

You can use a catch block to handle all exceptions that may be generated in the try block.

The catch block specifies an identifier ( catchID in the preceding syntax) that holds the value specified by the throw statement. You can use this identifier to get information about the exception that was thrown.

JavaScript creates this identifier when the catch block is entered. The identifier lasts only for the duration of the catch block. Once the catch block finishes executing, the identifier no longer exists.

For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.

Note: When logging errors to the console inside a catch block, using console.error() rather than console.log() is advised for debugging. It formats the message as an error, and adds it to the list of error messages generated by the page.

The finally block

The finally block contains statements to be executed after the try and catch blocks execute. Additionally, the finally block executes before the code that follows the try…catch…finally statement.

It is also important to note that the finally block will execute whether or not an exception is thrown. If an exception is thrown, however, the statements in the finally block execute even if no catch block handles the exception that was thrown.

You can use the finally block to make your script fail gracefully when an exception occurs. For example, you may need to release a resource that your script has tied up.

The following example opens a file and then executes statements that use the file. (Server-side JavaScript allows you to access files.) If an exception is thrown while the file is open, the finally block closes the file before the script fails. Using finally here ensures that the file is never left open, even if an error occurs.

If the finally block returns a value, this value becomes the return value of the entire try…catch…finally production, regardless of any return statements in the try and catch blocks:

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

Nesting try. catch statements

You can nest one or more try. catch statements.

If an inner try block does not have a corresponding catch block:

  1. it must contain a finally block, and
  2. the enclosing try. catch statement’s catch block is checked for a match.

For more information, see nested try-blocks on the try. catch reference page.

Utilizing Error objects

Depending on the type of error, you may be able to use the name and message properties to get a more refined message.

The name property provides the general class of Error (such as DOMException or Error ), while message generally provides a more succinct message than one would get by converting the error object to a string.

If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn’t discriminate between your own exceptions and system ones), you can use the Error constructor.

Источник

Smartadm.ru
Adblock
detector