What is exception propagation?
Give an example of a class that contains at least two methods, in which one method calls another. Ensure that the subordinate method will call a predefined Java method that can throw a checked exception. The subordinate method should not catch the exception. Explain how exception propagation will occur in your example.
Exception Propagation:- It is a process in which a method instead of handling checked exceptions itself, it transfers the exception to the caller of the method:-
Example of Exception Propagation in JAVA:-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionPropagation {
public void method1() throws IOException { // here
in this method instead of handling the exception itself, it is
throwing the exception to the caller itself
FileReader file = new
FileReader("C:\\test.txt");
BufferedReader fileInput = new
BufferedReader(file);
//print the contents of
file
while(fileInput.read() != -1)
{
System.out.print(fileInput.read());
}
fileInput.close();
}
public void method2() {
//Exception should be handled while
calling the method1() here
try {
method1();
} catch (IOException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
Get Answers For Free
Most questions answered within 1 hours.