In: Computer Science
Exercise 2:
Try-Catch Exercise
Write a Java code that does the following:
Create a class MyClass and create three methods myMethod1(), Method2() and Method3().
Invoke Method2() from Method1() and Method3() from Method2().
Write a code that can throw an exception inside myMethod3() and compile:
File file=new File("filename.txt");
Scanner sc=new Scanner(file);
You will get compilation errors now, as you are not handling a checked exception FileNotFoundException.
Declare throws over myMethod3() and myMethod2(). You will need to add throws FileNotFoundException on myMethod() as:
public void myMethod3() throws FileNotFoundException
{
File file=new File("filename.txt");
Scanner sc=new Scanner(file);
}
Handle the exception in myMethod1() by enclosing the code that can throw exception using a try-catch block:
public void myMethod1()
{
try{
myMethod2();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
Program
import java.util.*;
import java.io.*;
public class MyClass {
public void myMethod1(){
try {
myMethod2();
} catch(FileNotFoundException e) {
e.printStackTrace();
}
}
public void myMethod2()throws FileNotFoundException {
myMethod3();
}
public void myMethod3() throws FileNotFoundException {
File file=new File("filename.txt");
Scanner sc=new Scanner(file);
}
public static void main(String args[]){
MyClass m=new MyClass();
m.myMethod1();
}
}