Exceptions and Assertions Flashcards
Throw and Throws definition
Throw means an exception is actually being thrown
Throws indicates that the method merely has the potential to thrw that exception to the calling method
What should we decide on creating our own exception class?
We should decide on whether it should be checked or unchecked exceptions
Three most common constructors defined by the Exception classes
1. public someclass(){ {super();} 2. public someclass(Exception e){ super(e); } 3. public someclass(String message){ super(message); }
How to print the stack trace of our own?
e.printStackTrace();
what are the two approaches before java 1.7 for catching multiple exceptions?
- To have multiple catch clause to catch each of the expected exceptions and handle them
- To have a same method defined in each catch class that handles the exception
What is the approach after 1.7 for catching multiple exceptions?
Use multi-catch approach
Syntax of multi-catch
1. try{ } catch(Exception 1 | Exception 2 e){ // exception handler }
- Catch(Exception1 e1 | Exception2 e2| Exception3 e3)
- catch(Exception1 | Exception2 | Exception3 e)
- catch(Exception1 e| Exception2 e| Exception3 e)
Which one compiles?
2 one compiles.
Does java allows you to specify redundant types in multi-catch?
No, compiler throws the error
catch(FileNotFoundException | IOException e).
What happens?
Exception is thrown.
The Exception FileNotFoundException is already caught by the alternative IOException
Can we reassign a variable in a catch block in normal single catch Block. Is the below one legal?
Eg.., try{ } catch(RuntimeException e) { e = new RuntimeException(); }
Yes it is legal, this is allowed but we should avoid using like this.
Is this allowed? try{ throw new IOException(); }catch (IOException | RunTimeException e){ e=new RuntimeException(); }
No, It is not allowed in multicatch statements.
Multi-catch are effectively final.
What is the issue with finally clause?
The finally clause may have some redundant codes because it should close all the resources
what does java 7 introduces for managing the resources automatically?
try-with-Resources approach
What is the Try-With-Resources class called as?
Automatic Resource Management
Can we have the catch/Finally clauses still used in try-with-resources approach?
Yes, we can still have the catc/finally with Try-with-resources approach