Throws
Throws
import java.io.FileNotFoundException;
import java.io.FileReader;
//(1)
public class Read
{
public static void main(String[] args)
{
FileReader fr=new FileReader("D:/ab.txt"); //Reading A file
System.out.println("hello");
}
}
CompileTime Error
Read.java:9: error: unreported exception FileNotFoundException; must be caught or
declared to be thrown
FileReader fr=new FileReader("D:/ab.txt");
^
import java.io.FileNotFoundException;
import java.io.FileReader;
//(2)
public class Read
{
public static void main(String[] args)throws FileNotFoundException
{
FileReader fr=new FileReader("D:/ab.txt");
System.out.println("hello");
}
}
Exception in thread "main" java.io.FileNotFoundException: D:\ab.txt (The system
cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:111)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at Read.main(Read.java:9)
Note:
Abnormal Termination of program .
“Hello” not printed .
Exception Object provided by main method to JVM.
Exception Not handled By Throws keyword
import java.io.FileNotFoundException;
import java.io.FileReader;
//(3) Exception Handling Using Try Catch
public class Read
{
public static void main(String[] args)throws FileNotFoundException
{
try
{
FileReader fr=new FileReader("D:/ab.txt");
}
catch(FileNotFoundException e)
{
System.out.println(e);
System.out.println("hello");
}
}
}
import java.io.FileNotFoundException;
import java.io.FileReader;
//(3)
public class Read
{
void read()throws FileNotFoundException
{
FileReader fr=new FileReader("D:/ab.txt");
System.out.println("hello");
}
}
class ReadFile
{
public static void main(String[] args)throws FileNotFoundException
{
Read r=new Read();
r.read();
System.out.println("Exception Handled");
}
}
import java.io.FileNotFoundException;
import java.io.FileReader;
//(4)
public class Read
{
void read()throws FileNotFoundException
{
FileReader fr=new FileReader("D:/ab.txt");
System.out.println("hello");
}
}
class ReadFile
{
public static void main(String[] args)//Not Recomended to use throws Here
{
Read r=new Read();
try
{
r.read();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
System.out.println("Exception Handled");
}
}
Output
hello
Exception Handled