Java Exceptions Flashcards

1
Q

What are exceptions in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain the Exception hierarchy in Java.

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do exceptions work in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are errors in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Explain unchecked exceptions.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the exception handling keywords in Java?

A
  1. throw: when we want to explicitly throw an exception to runtime environment
  2. 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.
  3. 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.
  4. try-with-resources: when we want to close the resources after program is finished but also want to handle the exceptions.
  5. finally: optional block with try-catch block containing statements for closing resources. It will always get executed whether or not exception occurs.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain the Java 7 ARM feature.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the similarities and differences between try-with-resources and finally block?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Explain the multi-catch block.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between checked and unchecked exceptions?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can we create custom exceptions in Java?

A

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( );
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the direct subclasses of RuntimeException?

A
ArithmeticException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
UnsupportedOperationException
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is OutOfMemoryError in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is java.lang.UnsupportedClassVersionError?

A

This error is thrown when there is JDK version mismatch between the compilation and execution of a Java class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between final, finally and finalize in Java?

A

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:

  1. final variable: is actually a constant and cannot change its value anywhere in the program
  2. final method: cannot be overridden by any method anywhere
  3. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What happens when main( ) throws an exception and is not caught?

A

The exception is thrown to JVM which terminates the main( ) method and prints the exception stack trace.

17
Q

Identify and correct the problem with below code.

try {
//code
} catch (FileNotFoundException | IOException e) {
//logging
}
A

As FileNotFoundException is a subclass of IOException and we are providing same handler code for both the exceptions, JVM will give compile-time error saying that “FileNotFoundException is already caught by the alternative IOException”.

We can correct it one of two ways:

try {
			//code
		} catch (FileNotFoundException e) {
			//logging
		}catch(IOException e) {
			//logging
		}

or

try {
			//code
		}catch(IOException e) {
			//logging
		}
18
Q

Identify and correct the problem with below code.

try {
			//code
		}catch(IOException e) {
			//logging
		}catch (FileNotFoundException e) {
			//logging
		}
A

As catch block catching IOException is provided first, all of its subclasses including FileNotFoundException will be caught by it, rendering FileNotFoundException catch block unreachable.

To correct it, we need to change the order or remove FileNotFoundException catch block altogether.

19
Q

Identify and correct the problem with below code.

try {
foo( );
} catch ( IOException e ) {
//logging
}catch( JAXBException e ){
//logging
}catch( NullPointerException e ){
//logging
}catch( Exception e ){
//logging
}
void foo( ) throws IOException{
		//code
	}
A

As JAXBException is a checked exception, it must be thrown by the method foo( ), which it is not doing. Hence the compiler will show message “JAXBException is never thrown from the try statement body”.

As NullPointerException is an unchecked exception, it is not mandatory for a method to throw it.

20
Q

Identify and correct the problem with below code.

try{
bar( );
}catch( NullPointerException e ){
	//logging		
}catch( Exception e ){
//logging			
}

foo();

public void bar( ){
	//code	
}
public void foo( ) throws NullPointerException{
	//code	
}
A

There is no problem with the code- it is not mandatory to throw nor catch NullPointerException which is an unchecked exception.

21
Q

Identify and correct the problem with below code.

public class MyException1 {

public void start( ) throws IOException{		
}

public void foo( ) throws NullPointerException{

}

}

public class MyException2 extends MyException1 {

public void start( ) throws Exception{
}

public void foo( ) throws RuntimeException{

}

}

A

The methods in class MyException2 override the ones in class MyException1 and the rule for exceptions in overriding methods is this:

  1. For an unchecked exception: An overriding method can throw any unchecked exceptions, regardless of whether the overridden method throws exceptions.
  2. For a checked exception: the overriding method cannot throw checked exceptions that are new or broader than the ones declared by the overridden method

The code here violates the 2nd rule.

To correct it, we can either make start( ) method in MyException2 class throw subclass of IOException (like FileNotFoundException) or not throw any exception at all.

22
Q

Identify and correct the problem with below code.

try {
foo( );
} catch  (IOException | JAXBException e) {
e = new Exception("");
}
A

As Exception object is final, it cannot be assigned another value. The code will give compile-time error “The parameter e of a multi-catch block cannot be assigned”.

23
Q

Identify and correct the problem with below code.

public class MyException1 {

public void start( ) {		
} }

public class MyException2 extends MyException1 {

public void start( ) throws FileNotFoundException{
}

}

A

If the overriding method throws a checked exception, the overridden method must throw same exception or parent exception.