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
Can we have 2 or more finally blocks in traditional tryblocks?
No, it is not legal,
What is the scope of resources declared in try-with-resources block?
Its scope is only to try blocks. It cannot be accessed in the catch or finally blocks
try(Scanner s = new Scanner(System.in)){ s.nextLine(); } catch(Exception e) { s.nextInt(); } finally{ s.nextInt(); }
what is the output?
It doesnt compile. Bacuse the scope of the scanner is with in try only
What is the criteria of declaring a resource in try with resources block?
The resource should implement AutoCloseable interface.
What will happen here?
try(SomeClass class = new SomeClass()) { System.out.println(class); }
Exception: The resource type Turkey doesnot implement java.lang.AutoCloseable interface
What is the method to be overridden for AutoCloseable interface?
public void close() throws Exception;
what is idempotent?
Idempotent means that the method can be called multiple times without any side effects or change of state
public class AutoCloseableIssue implements AutoCloseable {
@Override public void close() throws Exception{ throw new Exception(); }
public static void main(String[] args) { try(AutoCloseableIssue issue = new AutoCloseableIssue()){ System.out.println("Hello"); } } }
What happens to this code?
The code doesnt compile because the close method throws an Exception and the place where this class is declared in try with resources has not caught tis Exception. So, it throws error
What does Java recommends for close method()
- close() method not throw Exception
- It is better to throw any specific Exception
- The close method should be idempotent
What are the difference between Closeable and AutoCloseable interface?
- The closeable restricts the specific type of exception thrown to be IOException
- Closeable requires implementation to be Idempotent
What should we do when the close() method throws an Exception?
We must handle that exception. SO, we must have a catch block to catch that Exception.
Since, the try-with-resource automatically calls the Close(), if it throws an exception, we need to handle it with catch clause.
When multiple exceptions are thrown in try-with-resources, what are the first exception called?
All but the first exceptions are called as ‘Suppressed Exceptions’
What is the output of the below code:
@Override public void close() throws Exception{ throw new Exception("Suppressed"); }
public static void main(String[] args) { //throws Exception{ try(AutoCloseableIssue issue = new AutoCloseableIssue()){ throw new IllegalStateException("This is primary"); } catch(Exception e){ System.out.println("caught: " + e); for(Throwable e1 : e.getSuppressed()){ System.out.println(e1.getMessage()); } } }
caught: java.lang.IllegalStateException: This is primary
Suppressed
What happens if the primary exceptions thrown doesnt match with the Exception type declared in ‘catch’ block? Does we get compiler error?
- It eventually throws the exception to the caller and prints the stack trace. No we don’t get compiler error
what is the output of thie below?
static int i = 0; @Override public void close() throws RuntimeException{ throw new RuntimeException("from close " + i++ ); }
public static void main(String[] args) { //throws Exception{ try(AutoCloseableIssue issue1 = new AutoCloseableIssue(); AutoCloseableIssue issue2 = new AutoCloseableIssue()){ System.out.println("Hello");; } catch(RuntimeException e){ System.out.println("caught: " + e); for(Throwable e1 : e.getSuppressed()){ System.out.println(e1.getMessage()); } } }
Hello
caught: java.lang.RuntimeException: from close 0
from close 1
What does the suppressed exception applicable only to?
The suppressed exception is applicable only to ‘try clause’
What exception does this throw? static int i = 0; @Override public void close() throws RuntimeException{ throw new RuntimeException("from close " + i++ ); }
public static void main(String[] args) { //throws Exception{ try(AutoCloseableIssue issue1 = new AutoCloseableIssue(); AutoCloseableIssue issue2 = new AutoCloseableIssue()){ System.out.println("Hello");; } finally{ throw new RuntimeException("And we lost others"); }
java.lang.RuntimeException: And we lost others
at com.org.AutoCloseableIssue.main(AutoCloseableIssue.java:17)
What should we keep in mind always on using try-with-resources statement
- Resources are closed after the try clause ends and before any catch/finally clause runs
- Resorces are closed in reverse order from which they are created.
What to keep on mind on rethrowing an exception?
If we call a method that throws some exception, we can catch them by having
catch(Exception e) in our code.
Java considers only the exceptions that are thrown.
Which means ‘Exception type’ in the catch block, but it really means limited set of exceptions and doesnt need to keep on changing the catch blocks while adding or updating any exceptions in method signature.
More info on 305-306 page
What are assertions?
Assertions are boolean expressions that you place at a point that you consider to be true
Syntax for Assert expressions?
assert boolean_expression
assert boolean_expression : error_message
What type of error does assertion throws if it fails?
AssertionError. Since programmers cannot catch Error, assertion failures are fatal and ends the program
command to enable assertions
java -ea Class_name
(or)
java -enableassertions class_name
Which are the all the classes the assertions are enabled when using -ea without arguments
all classes except System class
syntax for enabling the assertins only for classes in a package and its sub packages
java -ea package_name… class_name.Main
Close look on 3 dots. It means any class in package or subpackages
How can we disable assertions?
-da or -disableassertions