pls find the code below:
public static void selectDefinition(String defName)
{
driver.findElement(By.xpath("//table[#id='MainContent_gdvDefs_DXMainTable']//td[text()='"+defName+"']")).click();
}
and
try{
selectDefinition(defdelname);
System.out.println("Definition "+defdelname+" was not removed from the table");
}
catch (Exception ex)
{
System.out.println("Definition "+defdelname+"was removed successfully from the table");
}
in the above code if the "defdelname" is deleted the catch block is not executing but for selectDefinition it is throwing no such element exception.
i am a beginner pls help me out...to solve this issue i want the catch block to be executed any workaround for that?
You have to add throws Exception to your method, in this way the exception is thrown to the calle inside the try/catch block and correctly handled:
public static void selectDefinition(String defName) throws Exception
{
driver.findElement(By.xpath("//table[#id='MainContent_gdvDefs_DXMainTable']//td[text()='"+defName+"']")).click();
}
This is NOT how exceptions are meant to work. They are used to alert that an error has occured during the execution of your program and not to manage your program workflow. Also in your code you are using the catch block to report a successful status, the opposite of what an exception catch is for.
If your method can de both succesfull and not (it is a possible outcome to remove and to not being capable of remove from the table, according to your example) you should use a return statement with a meaningful value, such as a boolean true \ false variable. Exception should occur only if the behavior that created it was NOT meant to occur.
Related
This might be a really dumb question to most of you here, really sorry about that. I am new to java and the book i am reading didn't explain the working of an example in it.
public class CrazyWithZeros
{
public static void main(String[] args)
{
try
{
int answer = divideTheseNumbers(5, 0);
}
catch (Exception e)
{
System.out.println("Tried twice, "
+ "still didn't work!");
}
}
public static int divideTheseNumbers(int a, int b) throws Exception
{
int c;
try
{
c = a / b;
System.out.println("It worked!");
}
catch (Exception e)
{
System.out.println("Didn't work the first time.");
c = a / b;
System.out.println("It worked the second time!");
}
finally
{
System.out.println("Better clean up my mess.");
}
System.out.println("It worked after all.");
return c;
}
}
I can't figure out where the control will go after another exception is generated in catch block in divideTheseNumbers() method ?
Any help will be appreciated !
Output for your program will be
Didn't work the first time.
Better clean up my mess.
Tried twice, still didn't work!
Didn't work the first time. - because of the catch block in divideTheseNumbers
Better clean up my mess. - because of the finally block in divideTheseNumbers
Tried twice, still didn't work! - because of the catch block in the main method.
In general when a exception is thrown from a method and if is not in a try block, it will be thrown to it's calling method.
There are two points to note :
1) Any exception that is not in a try block will be just thrown to
it's calling method(even if it is in a catch block)
2) finally block is always executed.
In your case, you are getting the second exception in catch block, so it will be thrown. But before exiting any method it will also execute finally block(finally block is always executed). That is why Better clean up my mess is also printed.
Some points regarding exception handling:
1. Place your code that may causes exception inside the try{} block.
2. Catch the appropriate exception using the catch block.
3. While catching exception it's better use more specific type exception instead of catching the generic exception like. For example you catch the Exception, in this case you may catch the more specific type exception ArithmeticException.
4. finally block always executed, even though you use return statement in catch or try block.
5. A method either throws or catch an exception. If a method catch an exception then for it is not required to throws the exception.
6. All exception need not to be handled by using catch-block. We can avoid the try-catch block for the unchecked exception like - ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException. See here for more.
You may also check the tutorial for learning more about exception handling.
If you run following code then it will compile and run successfully,
public class Example {
public static void main(String[] args) {
// insert code here
try {
new Example().go();
// throw new OutOfMemoryError();
} catch (Error e) {
System.out.println(e);
}
}
void go() {
go();
}
}
With following output :
java.lang.StackOverflowError
So my question is "Can we catch an Error"..??
Answer to your question is yes, you can catch error in java. And your code is almost correct. Your method go() calls itself infinitely and therefore causes StackOverflowError that is caught in your catch block and printed by System.out.println()
Yes, you can catch an Error, but you are advised not to do it, since Errors indicate serious problems that a reasonable application should not try to catch. (as stated in the Javadoc of Error)
Yes, we can catch an error.
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the throw statement.
Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purpose of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.
try {
while(true) {
}
} catch (Throwable e) {
// TODO: handle exception
System.out.println(e);
}
Note that there's a difference between StackOverflowException and StackOverflowError, since you have an error, it's a serious indication that you should never try to catch it.
Just don't do infinite things in your code, when this error happens, no stack space is available, how would you want to proceed?
StackOverFlowError indicates that you have severe problems, it's a bad idea to catch this error, instead, try to understand what problems you have in your code and fix them.
What is the difference between "finally" and write after "catch"?
For example:
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
} finally {
return true;
}
}
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
}
return true;
}
First of all, the only idiom that can even be considered a candidate is this:
try {
// stuff
} catch (Throwable t) {
// handle
}
// finally stuff
Note the caught type. Only if you catch any possible exception, including such dark monsters as ThreadDeath and VirtualMachineError can you hope to unconditionally reach the code below the try-catch.
But, that's only where it begins. What if the handling code itself throws an exception? So you need at least
try {
// main stuff
} catch (Throwable t) {
try {
// handle
} catch (Throwable t) {
// no code allowed here! Otherwise we descend into
// infinite recursion
}
}
// finally stuff
Now you may be beginning to realize the benefits of finally, but that's not all. Consider a quite typical scenario:
try {
// main stuff, may throw an exception. I want the exception to
// break what I'm doing here and propagate to the caller.
return true;
} finally {
// clean up, even if about to propagate the exception
}
How do you rewrite this? Without code duplication, impossible.
In the code you have provided there is no difference. But finally is used to run some piece of code after the try block no matter whether there is an exception or not.
Interesting point to make here is, we should avoid to return from the finally block because it can create confusion in scenarion when we return something from try block as well. Consider this piece of code:
try {
return true;
}
finally {
return false;
}
Now this code will return false no matter what happens in try. In many ways this behaviour is exactly consistent with the colloquial understanding of what finally means - "no matter what happens beforehand in the try block, always run this code." Hence if you return true from a finally block, the overall effect must always to be to return true, no?
In general, this is seldom a good idiom, and you should use finally
blocks liberally for cleaning up/closing resources but rarely if ever
return a value from them.
No difference in Your case. but
The runtime system always executes the statements within the finally block regardless of what happens within the try block.
So it's the perfect place to perform cleanup.
Note that if you're using JDK 7+, then most uses of the finally block can be eliminated, simply by using a try-with-resources statement.
We use try block, catch block and finally block to handle Exception in our program. A program may be have check or unchecked Exception. so this block are are used to handle those Exception. In the try block we mention or write those code which may be cause of an Exception and if we want that our code will be run if Exception occurred Then we write those code in the catch block. finally is a very special block which give us a special feature that if our catch block doesn't run then before the program goes to terminate that finally block code definitely execute. mostly this is use to save our data during unwanted program termination. if we use try block then there must be a catch block after the try block but finally is an optional not compulsory.
First thing to understand in this question is "why we use try{ } catch{ } block" Ok.
The answer is,when there is a possibility of our code of throwing an exception.
These kind of code we put in try{... } block &
catch {...} block contain the code to catch the exception generated by code in try{ } block.
Finally{...} block contain the code executed immediately after try{} catch{} block when try{ } block throws an exception.
e.g When you visit some website,but do to some server side problem it couldn't and page display some kind of message like "404 error or server is updating",these kind of code is written in finally block.
this simple catch only is for catch eXception and process it, but finally, execute if Exception or not , for example for close connections.
Finally block is useful to cleanup your code like closing open streams.
E.g:
File f = new File("\file.txt");
FileStream fs;
try{
fs = new FileStream(f);
} catch (IOException ioe){
ioe.printStackTrace();
} finally {
if (fs != null) {
fs.close() // close the stream
}
}
As your code only returning true/false , so it won't impact much . But think for any other code/logic where some mandatory/cleanup code is written to execute.
Also, it will difficult to catch all the exceptions via our code or in other words, we should catch specific exceptions which we can handle. At that point , finally will be real savior, as it will always execute(other than System.exit() or in some recursion case).
Also, for bringing the consistency in our code, one should always use finally block to perform any clean up code.
You may refer the below posts too for more clarification:
Using finally block vs writing code after the try/catch block
Try-catch-finally-return clarification
First Case:
If exception occurred in try block then catch block would be executed, and while serving the same catch block if there is again exception occurred then finally block would execute.
Second Case:
If exception occurred in try block then catch block would be executed, and if there is further exception in the same catch block then "return true;" would execute.
finally() is used whenever we want that some line of code should be executed even if exception occurs
But if u write line of code after catch it will not execute if exception occurs..
Today at work, I had to review a code snippet that looks similar to this mock example.
package test;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ExceptionTester {
public static Logger logger = Logger.getLogger(ExceptionTester.class);
public void test() throws IOException {
new IOException();
}
public static void main(String[] args) {
ExceptionTester comparator = new ExceptionTester();
try {
try {
comparator.test();
} finally {
System.out.println("Finally 1");
}
} catch(IOException ex) {
logger.error("Exception happened" ex);
// also close opened resources
}
System.out.println("Exiting out of the program");
}
}
It's printing the following output.I expected an compile error since the inner try did not have a catch block.
Finally 1
Exiting out of the program
I do not understand why IOException is caught by the outer catch block. I would appreciate if anyone can explain this, especially by citing stack unwinding process
A finally block represents a task that has to be done under both normal and abnormal conditions.
Example: You take an interview candidate to lunch. While at lunch, you find out he's wanted by the police for murder. Exception! Lunch is over, the interview is a total loss, but... you still have to pay for lunch.
try {
meetForLunch(interviewCandidate);
}
finally {
lunchBill.pay();
}
Note that paying for lunch hasn't taken care of the exception, you've still got to do something about the murderer at your interview. It's just a loose end that has to be taken care of before processing with damage control.
Most finally blocks are used in that way: A file needs to be closed whether you successfully saved the data or not, a database connection needs to be closed whether the transaction was approved or not, etc.
And the exception continues outward on its merry way, looking for a matching catch block in an enclosing scope.
Note that finally blocks will always run unless the process ends while the try block is still executing.
I think the problem is that your function
public void test() throws IOException {
new IOException();
}
Doesn't actually throw an exception - it just creates a new IOException() object. Changing this to
public void test() throws IOException {
throw new IOException();
}
should fix this.
The code above does not require much of an explanation - not definitely involving call stacks!. What is your confusion?did I miss something?
Here is my explanation
First point
You don't need both a catch and a
finally block. You can have one of
them or both of them with a
try-block, but not none of them.
The code inside the finally clause
will always be executed, even if an
exception is thrown from within the
try or catch block. If your code has
a return statement inside the try or
catch block, the code inside the
finally-block will get executed
before returning from the method.
So in the above code, an exception was never thrown (because you are not using throw in the test() method)
However, finally block got executed as promised by the the language spec and you got the output Finally 1. The next statement in the sequence of execution is the System.out.println("Exiting out of the program"); as the catch block never reached as there are no IOExceptions. So, Exiting out of the program is printed.
This question already has answers here:
Why use finally
(9 answers)
Closed 1 year ago.
As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?
Code A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Code B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
What happens if you return from inside the try block?
What happens if the catch block throws an exception?
A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.
Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}
You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.
Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.
For example:
conn c1 = new connection();
try {
c1.dosomething();
} catch (ExceptionA exa) {
handleexA();
//c1.close();
} catch (ExceptionB exb) {
handleexB();
//c1.close();
} finally {
c1.close();
}
Finally always gets executed, where as your code after the catch may not.
Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...
Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.
In some cases finally won't execute such as JVM Fail, Thread terminate, etc.
Still scrolling down? Here you go!
This question gave me tough time back a while.
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
what would be printed in the above scenario?
Yes guessed it right:
ex.Message--whatever it is (probably attempted division by zero)
Finally block
After finally
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
What would this print? Nothing! It throws an error since the catch block raised an error.
In a good programming structure, your exceptions would be funneled, in the sense that this code will be handled from another layer. To stimulate such a case i'll nested try this code.
try
{
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block")
}
console.writeline("After finally");
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
In this case the output would be:
Finally block
ex.Message--whatever it is.
It is clear that when you catch an exception and throw it again into other layers(Funneling), the code after throw does not get executed. It acts similar to just how a return inside a function works.
You now know why not to close your resources on codes after the catch block.Place them in finally block.
Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).
There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses finally.
finally ALWAYS executes, unless the JVM was shut down, finally just provides a method to put the cleanup code in one place.
It would be too tedious if you had to put the clean up code in each of the catch blocks.
If catch block throws any exception then remaining code will not executed hence we have to write finaly block.
finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).