answersLogoWhite

0

What are the try catch and finally?

Updated: 8/11/2023
User Avatar

Wiki User

10y ago

Best Answer

final is a keyword that is used for variables, methods and classes. It means that the variable cannot be modified, the method cannot be overridden and the class cannot be inherited.

finally is a keyword that is used in try-catch blocks to ensure that a certain piece of code will execute irrespective of whether an exception occurred or not. For example in places where we access the database, we will close the connection in the finally block to ensure that the connection is released to the connection pool even if the query failed with some exception.

User Avatar

Wiki User

14y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

14y ago

The try-catch-finally block is an exception handling block of code.

The keyword try tells Java that it should try to run the following block of code. If it encounters an Exception, it will try to match it up to one of the catch blocks.

Let's use an example where we're trying to change the LookAndFeel of out GUI objects (mostly because it can throw a lot of different exceptions).

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch(Exception ex) {

System.out.println("Cannot change LookAndFeel");

}

But using Exception as a catch-all isn't always what we want to do. We know that our line of code may throw various different types of exceptions, so let's take advantage of that.

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException ex) {

System.out.println("Cannot change LookAndFeel - LnF not found");

} catch (InstantiationException ex) {

System.out.println("Cannot change LookAndFeel - Cannot instantiate LnF");

} catch (IllegalAccessException ex) {

System.out.println("Cannot change LookAndFeel - Access not allowed");

} catch (UnsupportedLookAndFeelException ex) {

System.out.println("Cannot change LookAndFeel - LnF not supported");

}

This brings us to the finally keyword. Unlike try or catch, finally is optional. It tells Java that no matter what happens in the try or catch blocks, we want to execute this code immediately afterward.

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException ex) {

System.out.println("Cannot change LookAndFeel - LnF not found");

} catch (InstantiationException ex) {

System.out.println("Cannot change LookAndFeel - Cannot instantiate LnF");

} catch (IllegalAccessException ex) {

System.out.println("Cannot change LookAndFeel - Access not allowed");

} catch (UnsupportedLookAndFeelException ex) {

System.out.println("Cannot change LookAndFeel - LnF not supported");

} finally {

System.out.println("Done!");

}

Note that the finally block has more uses than this, but the "it always happens after the try-catch block" explanation should work for us for now.

And this now brings us to the completely unrelated final keyword. This can be applied to classes, methods, or variables.

final class MyClass {

final int zero = 0;

final int getZero() {

return zero;

}

}

When applied to a class, the final keyword tells us that no other class can inherit from this class. It is declared as a "leaf" in its hierarchy tree.

Similarly, a method which is declared final means that no subclasses can override this method.

A variable that is set as final is essentially a constant. It means that the value you set it to cannot be changed later in your code. Note that when applied to something like a Collection or an array, this means that the reference to the Collection/array can not be changed. The data, however, can be changed.

final int[] nums = new int[3];

// This is legal

nums[0] = 1;

nums[0] = 2;

// This will cause an error

nums = new int[4];

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What are the try catch and finally?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

How do you get finally block in javascript to only execute if there are no errors are caught by catch block?

You might consider a construct like this: try { some code } catch (exception) { var err=1; } if (!err) { your finally block }


What is finally block in java?

The Finally block in java is used along with the try-catch statements. The usual structure is try { ..... } catch(Exception e){ .... } finally { ..... } In the finally block we usually have code that is used to perform clean up activities corresponding to the code in the try block. When an exception occurs in the try block control comes to the catch block and the rest of the code in the try block would not execute. In such cases we may need to have some code that cleans up the objects that we created/used in the try block. No matter what happens, the code inside the finally block would definitely execute. The best use of finally block is when we are connecting to the database. In the try block we would have the statements that instantiate the connection, prepared statement, result set etc. If the query fails then all these objects would be left open and the code would continue. So in the finally block we usually nullify these statements so that even in case of an error the unused objects are cleared. Example: Connection con; PreparedStatment PS; ResultSet rs; try{ con = ConnectionManager.getConnection(); PS = con.prepareStatement(query); rs = PS.executyQuery(); ...... } catch (Exception e){ e.printStackTrace(); } finally { con.close(); PS.close(); } In case of an error the connection & prepared statement objects would remain open if we do not have the finally block. Tip: Whatever code we have inside the finally block would be run definitely if the try block is invoked. We can even use the finally block to check if the try block was reached and executed. If the try executes then we can rest assured that the finally would also get executed.


What is finally statement in java?

Although try and catch provide a great way to trap and handle exceptions, we are left with the problem of how to clean up if an exception occurs. Because execution transfers out of the try block as soon as an exception is thrown, we can't put our cleanup code at the bottom of the try block and expect it to be executed if an exception occurs. Exception handlers are a poor place to clean up after the code in the try block because each handler then requires its own copy of the cleanup code. If, for example, you opened a database connection somewhere in the guarded region, each exception handler would have to release the connection. That would make it too easy to forget to do cleanup, and also lead to a lot of redundant code. If you forget to close the connection in cases where an exception occurs, you will be left with orphan connections which can eventually crash your database. To address this problem, Java offers the finally block. A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes! This is the right place to close your files, release your db connections, and perform any other cleanup your code requires. If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. If there was an exception thrown, the finally block executes immediately after the proper catch block completes. Let's look at another pseudocode example: 1: try { 2: // This is the first line of the "guarded region". 3: } 4: catch(DatabaseDownException) { 5: // Put code here that handles this exception 6: } 7: catch(SomeOtherException) { 8: // Put code here that handles this exception 9: } 10: finally { 11: // Put code here to release any resource we 12: // allocated in the try clause. 13: } 14: 15: // More code here As before, execution starts at the first line of the try block, line 2. If there are no exceptions thrown in the try block, execution transfers to line 11, the first line of the finally block. On the other hand, if a SomeOtherException is thrown while the code in the try block is executing, execution transfers to the first line of that exception handler, line 8 in the catch clause. After all the code in the catch clause is executed, the program moves to line 11, the first line of the finally clause. To summarize - THE FINALLY BLOCK WILL EXECUTE ALWAYS. There is actually a catch here about the finally block executing always, but I will leave you to ponder over it for sometime. We will look at it a little later.


A program to explain the Exception Handling mechanisms in Java using the keywords try catch and finally?

Here is a code snippet illustrating exception handling: try { int a= 3 / 0 ; } catch ( ArithmeticException e ) { System.out.println ("An ArithmeticException has occured"); } finally { // some code }


Explain about exception handling with multiple exception?

Exception handling in Java is done through a try-catch-finally block. The "try" block of code is where you put the code which may throw an exception. The "catch" block of code is where you put the code which will execute after an exception is thrown in the try block. This is often used to display an error message, or to mitigate problems caused by the exception. The "finally" block is where you put code that you want to execute after the try and catch blocks have been processed. // example code for catching exception while reading from a file try { // this line of code can throw a FileNotFoundException FileReader in = new FileReader("myfile.txt"); // this line of code can throw an IOException in.read(); } catch(FileNotFoundException ex) { // catch first exception type System.err.println("Cannot find myfile.txt!"); } catch(IOException ex) { //catch second exception type System.err.println("Cannot read from myfile.txt!"); } finally { // no matter what we want to close the file, so do it here // however, this line can also cause an exception, so we need to catch that, too try { in.close(); catch(IOException ex) { // not much we can do about an exception that occurs here } }

Related questions

How many finally block can be used for an exception handler?

Genaerally every try block maintain the one finally block or atleast one catch block or both. It mean try { try{ try{ } or } or } finally { catch(....) { catch(...){ } } } catch(.....) { : } finally{ : } Hear whenever we declar the try block without catch or finally bocks it show the compile time error like ' try without catch or finally' and also it is not possible to declare the any statements in between the try ,catch and finally blocks. ex: try{ } System.out.println("statement"); finally { } The above example show the compile time error 'try without catch or finally'. " Hear the finally block must be execute after excuting the try or catch block. Hence the finally block is used to release the resources like closing the streams and closing the jdbc connections." Hence in exception handling we use one finally block for one try block to release the resources.


Which is equivalent to try and finally block?

Try block is followed by finally block as an alternative . But usually it is followed by a catch block. Both are equivalent.


Can you catch multiple throwables in a try catch statement in Java?

Yes, the format of a try/catch/finally block is: try{ // Do Code } catch (Throwable A) { // Process throwable/exception } catch (OtherThrowable B) { // Process throwable/exception } // ... and so on and so forth, catching as many different catches as needed finally{ // Code you always want to execute, whether breaking out of a try // statement normally or by catching a throwable. // For example, close database connections or file handles here. }


How do you get finally block in javascript to only execute if there are no errors are caught by catch block?

You might consider a construct like this: try { some code } catch (exception) { var err=1; } if (!err) { your finally block }


Does try run without catch n exception handling?

A try block must have a corresponding catch or atleast a finally block. The purpose of a try block is to identify areas in the code where exceptions may be generated and handle them. So, if you dont have a catch block, the whole purpose of using the try block is defeated


How you do use finally keyword in java?

You use it in combination with "try" and "catch". Any commands after "finally" will be run whether there is an error or not. Cleanup commands are typically placed here.


What is finally block in java?

The Finally block in java is used along with the try-catch statements. The usual structure is try { ..... } catch(Exception e){ .... } finally { ..... } In the finally block we usually have code that is used to perform clean up activities corresponding to the code in the try block. When an exception occurs in the try block control comes to the catch block and the rest of the code in the try block would not execute. In such cases we may need to have some code that cleans up the objects that we created/used in the try block. No matter what happens, the code inside the finally block would definitely execute. The best use of finally block is when we are connecting to the database. In the try block we would have the statements that instantiate the connection, prepared statement, result set etc. If the query fails then all these objects would be left open and the code would continue. So in the finally block we usually nullify these statements so that even in case of an error the unused objects are cleared. Example: Connection con; PreparedStatment PS; ResultSet rs; try{ con = ConnectionManager.getConnection(); PS = con.prepareStatement(query); rs = PS.executyQuery(); ...... } catch (Exception e){ e.printStackTrace(); } finally { con.close(); PS.close(); } In case of an error the connection & prepared statement objects would remain open if we do not have the finally block. Tip: Whatever code we have inside the finally block would be run definitely if the try block is invoked. We can even use the finally block to check if the try block was reached and executed. If the try executes then we can rest assured that the finally would also get executed.


What is the use of a finally clause?

Finally is used in exception blocks:try{...}catch(...){...}finally{...}Finally is used if you need to do something in case if an exception was occurred. And if it cannot be done in the catch block.


A program to explain the Exception Handling mechanisms in Java using the keywords try catch and finally?

Here is a code snippet illustrating exception handling: try { int a= 3 / 0 ; } catch ( ArithmeticException e ) { System.out.println ("An ArithmeticException has occured"); } finally { // some code }


What is finally statement in java?

Although try and catch provide a great way to trap and handle exceptions, we are left with the problem of how to clean up if an exception occurs. Because execution transfers out of the try block as soon as an exception is thrown, we can't put our cleanup code at the bottom of the try block and expect it to be executed if an exception occurs. Exception handlers are a poor place to clean up after the code in the try block because each handler then requires its own copy of the cleanup code. If, for example, you opened a database connection somewhere in the guarded region, each exception handler would have to release the connection. That would make it too easy to forget to do cleanup, and also lead to a lot of redundant code. If you forget to close the connection in cases where an exception occurs, you will be left with orphan connections which can eventually crash your database. To address this problem, Java offers the finally block. A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes! This is the right place to close your files, release your db connections, and perform any other cleanup your code requires. If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. If there was an exception thrown, the finally block executes immediately after the proper catch block completes. Let's look at another pseudocode example: 1: try { 2: // This is the first line of the "guarded region". 3: } 4: catch(DatabaseDownException) { 5: // Put code here that handles this exception 6: } 7: catch(SomeOtherException) { 8: // Put code here that handles this exception 9: } 10: finally { 11: // Put code here to release any resource we 12: // allocated in the try clause. 13: } 14: 15: // More code here As before, execution starts at the first line of the try block, line 2. If there are no exceptions thrown in the try block, execution transfers to line 11, the first line of the finally block. On the other hand, if a SomeOtherException is thrown while the code in the try block is executing, execution transfers to the first line of that exception handler, line 8 in the catch clause. After all the code in the catch clause is executed, the program moves to line 11, the first line of the finally clause. To summarize - THE FINALLY BLOCK WILL EXECUTE ALWAYS. There is actually a catch here about the finally block executing always, but I will leave you to ponder over it for sometime. We will look at it a little later.


Explain about exception handling with multiple exception?

Exception handling in Java is done through a try-catch-finally block. The "try" block of code is where you put the code which may throw an exception. The "catch" block of code is where you put the code which will execute after an exception is thrown in the try block. This is often used to display an error message, or to mitigate problems caused by the exception. The "finally" block is where you put code that you want to execute after the try and catch blocks have been processed. // example code for catching exception while reading from a file try { // this line of code can throw a FileNotFoundException FileReader in = new FileReader("myfile.txt"); // this line of code can throw an IOException in.read(); } catch(FileNotFoundException ex) { // catch first exception type System.err.println("Cannot find myfile.txt!"); } catch(IOException ex) { //catch second exception type System.err.println("Cannot read from myfile.txt!"); } finally { // no matter what we want to close the file, so do it here // however, this line can also cause an exception, so we need to catch that, too try { in.close(); catch(IOException ex) { // not much we can do about an exception that occurs here } }


How do you beat Elesa in Pokemon black with Tepig?

you would have to evolve it and train it a lot and then try to beat her. if you still don't beat her try to catch other pokemon, level them up, finally you would have to beat her.