What does try do in java?

11,153

Solution 1

The try/catch/finally construct allows you to specify code that will run in case an exception has occured inside of the try block (catch), and/or code that will run after the try block, even if an exception has occured (finally).

 try{
    // some code that could throw  MyException;
 }
 catch (MyException e){
     // this will be called when MyException has occured
 }
 catch (Exception e){
     // this will be called if another exception has occured
     // NOT for MyException, because that is already handled above
 }
 finally{
     // this will always be called,
     // if there has been an exception or not
     // if there was an exception, it is called after the catch block
 }

Finally blocks are important to release resources such as database connections or file handles no matter what. Without them, you would not have a reliable way to execute clean-up code in the presence of exceptions (or return, break, continue and so on out of the try block).

Solution 2

try is used for exception handling.

http://java.sun.com/docs/books/tutorial/essential/exceptions/try.html

Solution 3

It allows you to attempt an operation, and in the event an Exception is thrown, you can handle it gracefully rather than it bubbling up and being exposed to the user in an ugly, and often unrecoverable, error:

try
{
    int result = 10 / 0;
}
catch(ArithmeticException ae)
{
    System.out.println("You can not divide by zero");
}

// operation continues here without crashing

Solution 4

try is often used alongside catch for code that could go wrong at runtime, an event know as throwing an exception. It is used to instruct the machine to try to run the code, and catch any exceptions that occur.

So, for example, if you were to request to open a file that didn't exist the language warns you that something has gone wrong (namely that it was passed some erroneous input), and allows you to account for it happening by enclosing it in a try..catch block.

File file = null;

try {
    // Attempt to create a file "foo" in the current directory.
    file = File("foo");
    file.createNewFile();
} catch (IOException e) {
    // Alert the user an error has occured but has been averted.
    e.printStackTrace();
}

An optional finally clause can be used after a try..catch block to ensure certain clean-up (like closing a file) always takes place:

File file = null;

try {
    // Attempt to create a file "foo" in the current directory.
    file = File("foo");
    file.createNewFile();
} catch (IOException e) {
    // Alert the user an error has occured but has been averted.
    e.printStackTrace();
} finally {
    // Close the file object, so as to free system resourses.
    file.close();
}

Solution 5

Exception handling

Share:
11,153
David
Author by

David

I'm David.

Updated on June 10, 2022

Comments

  • David
    David almost 2 years

    What does try do in java?