I have asked a question in aptitude test that a new try catch block can be inside a catch block or not?
For example
try {
} catch (Exception e) {
try {
} catch (Exception e) {
}
}
Is this valid in Java?
Yes it is possible tried following example with java8. it is working fine.
public static void main(String []args){
try{
System.out.println("try1");
throw new Exception("Exception1");
}catch(Exception e){
System.out.println("catch1");
try{
System.out.println("try2");
throw new Exception("Exception2");
}catch(Exception e1){
System.out.println("catch2");
}
}
}
Yes (given that you use upper/lower case correctly: try, catch, Exception)
Yes, It is possible because if any exception is occurs in try then it's catch and we want to add some logic or next implementation in catch block then we can.for example if we write code for get data in outer try block and getting any exception and we need add some logic like file releated or thread releated then we add and use try catch block in outer catch.
Related
Basically i have 2 different commands i could possibly execute. If the first one does not work, I want to execute the second command.
Is there some easier, cleaner way to do this?
What would i even put in the if statement?
try
{
// code that may throw an exception
driver.findElement(By.id("component-unique-id-31")).click();
}
catch (Exception ex)
{
// Print to console
}
if(previous command threw an exception){
try
{
//Another command i want executed if the above fails
driver.findElement(By.xpath("//h3[normalize-space()='Something']")).click();
}
catch (Exception ex)
{
// handle
}
}
You can put the second command inside the catch block of the first try-catch, as following:
try
{
// code that may throw an exception
driver.findElement(By.id("component-unique-id-31")).click();
}
catch (Exception ex1)
{
try
{
//Another command i want executed if the above fails
driver.findElement(By.xpath("//h3[normalize-space()='Something']")).click();
}
catch (Exception ex2)
{
// handle
}
}
You can wrap up both the try-catch{} blocks within a single try-catch-finally{} block as follows:
try {
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("component-unique-id-31"))).click();
System.out.println("Within in try block.");
}
catch(TimeoutException e) {
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//h3[normalize-space()='Something']"))).click();
System.out.println("Within in catch block.");
} finally {
System.out.println("The 'try catch' is finished.");
}
PS: You must avoid catching the raw exception.
public function() {
try {
// execute code and if error jump into 1st catch
return output;
} catch (Exception e){
//execute code and if error jump in 2nd catch
return output1
} catch (Exception e){
//execute code and stop
return output 2
}
}
The Above is the Code flow I want to achieve, I wanted to check if there is way or better way to do my scenario where I want to try a piece of code and if it fails, catch and execute first catch piece of code and if it again fails and exception occurs in first catch also go for final piece of code in last catch. Any help is very much appreciated. Thanks in advance.
Here is the flow I want to achieve :
try ----if error/exception----> catch1 ----if error/exception----> catch2
You can't do that. To catch a exception inside a catch block you should user another try/catch.
public function() {
try {
return output;
} catch (Exception e){
try {
return output1;
} catch (Exception e2) {
return output2;
}
}
}
Assuming we are talking about all the exceptions that extends base Exception class,
is:
try {
some code;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
catch (MyOwnException e)
{
e.printStackTrace();
}
same as:
try {
some code;
}
catch (Exception e) {
e.printStackTrace();
}
I am wondering in which case I MUST use the former one?
In the 2nd option Exception will catch all exception, not only those explicitly listed in the first option.
Use the 1st option if you want to catch only selected exceptions, and respond differently to each.
If you want to catch only selected exceptions, and have the same response to all of them, you could use:
catch (InterruptedException | ExecutionException | MyOwnException e)
{
e.printStackTrace();
}
It is good practice to use Exception sub classes rather than Exception class. If you use Exception then it would be difficult to debug.
Here is a link for reference
http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#3
If you have multiple exceptions which all are extending from...we'll say IndexOutOfBoundsException, then unless you specifically want to print a different message for StringIndexOutOfBoundsException or another sub-class you should catch an IndexOutOfBoundsException. On the other hand if you have multiple exceptions extending from the Exception class, it is proper format to create a multi-catch statement at least in JDK 1.8:
try {
// Stuff
}catch(InterruptedException | ClassNotFoundException | IOException ex) {
ex.printStackTrace();
}
The former one where you create multiple catch statements is if you were trying to do what I said before.
try {
// Stuff
}catch(StringIndexOutOfBoundsException se) {
System.err.println("String index out of bounds!");
}catch(ArrayIndexOutOfBoundsException ae) {
System.err.println("Array index out of bounds!");
}catch(IndexOutOfBoundsException e) {
System.err.println("Index out of bounds!");
}
I have a problem understanding how the try{} catch(Exception e){...} works!
Let's say I have the following:
try
{
while(true)
{
coord = (Coordinate)is.readObject();//reading data from an input stream
}
}
catch(Exception e)
{
try{
is.close();
socket.close();
}
catch(Exception e1)
{
e1.printStackTrace();
}
}
Section 2
try
{
is.close();
db.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Let's say my while() loop throws an error because of an exception of is stream.
This will get me out of the infinite loop and throw me in the first catch(){............}
block.
My question is the following:
After throwing an exception, getting out of the loop while() and reaching to
catch(){
}
Will my program continue his execution and move on to section 2? As long as the exception was caught? Or everything ends in the first catch()?
I think you want to use finally after your first catch [catch (Exception e)] to close your streams:
try {
// Do foo with is and db
} catch (Exception e) {
// Do bar for exception handling
} finally {
try {
is.close();
db.close();
} catch (Exception e2) {
// gah!
}
}
As long as no exceptions are thrown in your catch clause, your program will continue execution after your catch (or finally) clause. If you need to rethrow the exception from the catch clause, use throw; or throw new Exception(ex). Do not use throw ex, as this will alter the stack trace property of your exception.
After the exception is caught, execution continues after the try/catch block. In this case, that's your section 2.
An uncaught exception will terminate the thread, which might terminate the process.
Yes, you are right. It will move to Section 2.
If you want your Section 2 bound to happen, irrespective of any exception generated, you might want to enclose them in a finally block.
try {
// Do foo with is and db
}
catch (Exception e) {
// Do bar for exception handling
}
// Bound to execute irrespective of exception generated or not ....
finally {
try {
is.close();
db.close();
}
catch (Exception e2) {
// Exception description ....
}
}
What happens if you throw an error in a finally block? Does it get handled in one of the corresponding catch clauses?
Only if you put another try-catch block in the finally block. Otherwise it's an error like any other.
You need to include try-catch blocks inside the finally or catch blocks.
e.g.:
try {
// your code here
} finally {
try {
// if the code in finally can throw another exception, you need to catch it inside it
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
} catch (Exception e) {
try {
// your error handling routine here
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
}
It will not handle exception until it is caught in finally block it self.
public static void main(String[] args) throws Exception {
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
throw new Exception();
}
}
Above code will throw exception but if you do as follows it will work:
public static void main(String[] args){
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
try{
throw new Exception();
}catch(Exception e){}
}
}
Nope. It would be caught by a catch where then entire try/catch/finally was nested within another try/catch. The exception would otherwise be thrown out of the function, and would be handled by the caller of the function.
No it doesn't. You will have to handle with it IN the finally block or define a proper throw declaration in the method description.
No, a catch block can only catch exceptions thrown within the corresponding try block - not a finally block. (Of course, if that finally block is within another try block, the catch clauses for that try block are still used.)
The relevant section in the JLS is 14.20.2. Each of the flows listed there has something like this:
If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
In other words, there's no attempt for any catch clauses associated with the finally block to handle the exception.
The order of execution is normally directly indicated by the order of statements: 1. try, 2. catch exceptions in the specified order (only one catch is executed), 3. finally.
So when the finally block is executed (note that this is always the case, even in the case of a return statement or exception being thrown in the try or catch blocks) the execution of try statement is in its last phase and thus it cannot catch further throwables. As already pointed out, the exception has to be handled in a location further down the stack (or up, depends on the view point ;) ).