Java Exceptions Flashcards
What are exceptions in Java?
Exceptions are the problems that arise during the execution of a program. When an exception occurs, the normal flow of the program is disrupted and application terminates immediately.
For eg.
int a= 5, b=0;
int c=a/b;
will throw ArithmeticException.
Explain the Exception hierarchy in Java.
The object class is extended by class Throwable, which in turn is extended by classes Exception and Error.
Exceptions are problems arising during execution of program that can be handled and are of two types: checked and unchecked.
Checked exceptions are scenarios that compiler can predict at compile-time such as program trying to find a file might run into FileNotFoundException. These extend class Exception and its subclasses. For eg. IOException extends Exception and FileNotFoundException extends IOException.
Unchecked exceptions,also known as Runtime Exceptions, belong to a subclass of Exception- RuntimeException and are scenarios that compiler cannot predict such as program trying to call a method on a null object, causing NullPointerException. These are caused by programing errors.
Errors are problems arising during execution of program that cannot be handled because they are out of scope of the application. For eg. hardware failure, JVM crash or JVM running out of memory.
How do exceptions work in Java?
Whenever an exception occurs, an exception object is created and JRE tries to find the exception handler to handle it.
If suitable handler is found then exception object is passed to handler code for processing. This is called catching the exception.
If no handler is found then application throws the exception to runtime environment and JRE terminates the program.
What are errors in Java?
Errors are problems arising during execution of program that cannot be handled because they are out of scope of the application.
For eg.hardware failure, JVM crash or JVM running out of memory, network connection error etc.
Explain unchecked exceptions.
Unchecked exceptions,also known as Runtime Exceptions, belong to a subclass of Exception called RuntimeException and are scenarios that compiler cannot predict.
For eg. dividing by zero will throw ArithmeticException, trying to access an element in array outside its length will throw ArrayIndexOutOfBoundsException etc.
These occur due to programming error- such as not handling the scenario where dividend could be zero in a division operation or not checking if an object is null before calling a method on it.
These exceptions don’t have to be caught explicitly nor do they have to be declared. It is assumed that any method can throw them.
When an unchecked exception is thrown but is not caught by try-catch block, the application shows an error message printing the exception stack trace.
What are the exception handling keywords in Java?
- throw: when we want to explicitly throw an exception to runtime environment
- throws: when a method (even main( ) ) is throwing an exception and we do not want to handle it, rather we want the exception to propagate to its caller method. It is used in method signature and we can throw multiple exceptions.
- try-catch: when we are expecting an exception (try) and we want to handle it (catch). We can have multiple catch blocks for single try block.
- try-with-resources: when we want to close the resources after program is finished but also want to handle the exceptions.
- finally: optional block with try-catch block containing statements for closing resources. It will always get executed whether or not exception occurs.
Explain the Java 7 ARM feature.
Automatic Resouce Management (ARM) feature was introdcued in Java to reduce the situations where -resources are left unclosed, causing more errors.
This feature lets programmer create resources in try statement and use it inside try-catch block. When the execution is finished, the resources are automatically closed by runtime environment. The resource class must implement java.lang.AutoCloseable interface for its object to get automatically closed (meaning must override close( ) method).
For eg. below program reads first line from a file by using an instance of BufferedReader. BufferedReader is a resource that must be closed after the program is finished.
try ( BufferedReader br = new BufferedReader( new FileReader(path ) ) ) { return br.readLine( ); }
As BufferedReader implements AutoCloseable interface, its object can be declared in try statement and will be automatically closed once excecution is finished, no matter exception is thrown or not.
What are the similarities and differences between try-with-resources and finally block?
try-with-resources is a feature introduced in Java 7 which lets programmer create resources in try statement and use it inside try-catch block. When the execution is finished, the resources are automatically closed by runtime environment.
Prior to Java 7, this was done using finally block, although for a resource to be declared in try statement, it must implement AutoCloseable interface (meaning must override close( ) method).
For eg. the below method using try-with-resources :
String foo1 ( String path ) throws IOException { try (BufferedReader br = new BufferedReader( new FileReader (path) ) ) { return br.readLine( ); } }
can be re-written as:
String foo2 ( String path ) throws IOException { BufferedReader br = new BufferedReader ( new FileReader ( path ) ); try { return br.readLine ( ); } finally { if (br != null) br.close ( ); } }
However, in this example, if methods readLine( ) and close( ) both throw exception, the method foo2 throws exception thrown from finally block, suppressing exception thrown from try block.
In contrast, if exceptions are thrown from both try block and try-with-resources statement, the method foo1 throws an exception thrown from try block, suppresing the exception thrown from try-with-resources statement.
In Java 7 and later, suppressed exceptions can be retrieved by calling Throwable.getSuppressed method.
Explain the multi-catch block.
We can catch multiple exceptions with a try block and if we are providing the same logging in each catch block, then instead of duplicating the code, we can use multi-catch block.
For eg. instead of writing:
try{ //statement } catch (ArithmeticException e){ //logging } catch (FileNotFoundException e){ //logging }
we can write:
try{ //statement } catch (ArithmeticException | FileNotFoundException e){ //logging }
If we are catching exceptions who have parent-child relationship between them, the above format would not work and we would only need to specify parent exception.
For eg.
catch (FileNotFoundException | IOException e) would give compile-time error as FileNotFoundException is subclass of IOException and providing same handler code for both of them would not be allowed by compiler.
What is the difference between checked and unchecked exceptions?
Checked exceptions are scenarios predicted by compiler and must be handled in application using try-catch or throws keywords without which the compiler will give error.
Unchecked exceptions are scenarios caused by bad programming and not predicted by compiler, hence are not required to be handled.
class Exception is the superclass of checked exceptions whereas class RuntimeException is the superclass of unchecked exceptions. class Exception is eventually the superclass of class RuntimeException.
How can we create custom exceptions in Java?
We can extend Exception class or any of its subclass to create our custom exception class which can have its own variables and methods.
class MyException extends IOException {
private String message=”This is an unknown exception.”;
public String getErrorCode( ) {
return this.errorCode( );
}
What are the direct subclasses of RuntimeException?
ArithmeticException ClassCastException IllegalArgumentException IndexOutOfBoundsException UnsupportedOperationException
What is OutOfMemoryError in Java?
In Java, new objects are created in heap space and their references are stored in stack memory. Heap space is broken down into three generations- young, old and tenure and if the heap space gets full, we get java.lang.OutOfMemoryError.
What is java.lang.UnsupportedClassVersionError?
This error is thrown when there is JDK version mismatch between the compilation and execution of a Java class.
What is the difference between final, finally and finalize in Java?
final and finally are Java keywords whereas finalize is a method executed by Garbage Collector before an object is destroyed to make sure all the resources for that object are closed.
final keyword has three applications:
- final variable: is actually a constant and cannot change its value anywhere in the program
- final method: cannot be overridden by any method anywhere
- final class: cannot be extended by any class anywhere
finally keyword is used with try-catch block to provide statements that will be always executed.