Advertisement
//Declaring one checked exception using throws keyword
public void method1() throws IOException //method signature
{
}
//Declaring multiple checked exception using throws keyword
public void method2() throws FileNotFoundException, ParseException //method signature
{
}
Over here, the method1() has declared that it does not catch or handle IOException but only throws it. While, the method2() has declared in its signature,
that it does not handle either of two checked exceptions separated by commas, i.e. FileNotFoundException and ParseException.
//Java - Example of throws keyword
import java.io.*;
class ThrowsExm
{
public static void main(String... ar)
{
ThrowsExm ob= new ThrowsExm();
try
{
ob.fileRead();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
} //main method ends
public void fileRead() throws FileNotFoundException
{
File file = new File("D:\\File.txt");
FileReader fileReader = new FileReader(file); //Checked Exception is thrown here
}
} //class definition ends
Exception caught - java.io.FileNotFoundException: D:\File.txt (The system cannot find the file specified)
Advertisement
//Java - Using throws keyword with multiple checked exceptions
import java.io.*;
import java.util.*;
import java.text.*;
class A
{
public static void main(String... ar)
{
A ob= new A();
try
{
ob.writeAndDate();
}
catch(Exception e)
{
System.out.println("Exception caught - " + e);
}
} //main method ends
public void writeAndDate() throws IOException, ParseException
{
//Creating a new file and writing a message to it.
File file = new File("D:\\File.txt");
FileWriter fw = new FileWriter(file);
fw.write("Hello");
fw.flush();
fw.close();
//Converting a String to Date object
DateFormat df = DateFormat.getInstance();
Date d2= df.parse("100000000L"); //ParseException is thrown, parsing an unparseable String to Date object
System.out.println(d2);
}
}
Exception caught - java.text.ParseException: Unparseable date: "100000000L"
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement