Using throw keyword in exception handling in Core Java

This tutorial demonstrate how to use throw keyword in the exception handling of Core Java.

 
 

Share on Google+Share on Google+

Using throw keyword in exception handling in Core Java

Ads

This tutorial demonstrate how to use throw keyword in the exception handling of Core Java.

Description:

Core Java Throw Function is used for throwing the exception. The throw keyword tells the compiler that it will be handled by calling a method. It is used at any part of code and placed where you feel that  specific exception need to be thrown from the calling method.

Code for Java Throw Exception Handling:

package exceptionh;

import java.io.*;

class ExcepHandling1 {

public static FileInputStream file1(String fileName) {

FileInputStream fileInStrm = null;

try {

fileInStrm = new FileInputStream(fileName);

} catch (FileNotFoundException ex) {

System.out.println("caught exception" + ex.getMessage());

throw new Error("File not found");

}

System.out.println("File input stream created");

return fileInStrm;

}

public static void main(String args[]) {

FileInputStream fileIn;

String fileName = "myfile.ser";

System.out.println(" Starting of main" + " file name is " + fileName);

try {

fileIn = file1(fileName);

} catch (Exception ex) {

System.out.println("in main caught" + ex.getMessage());

} catch (Throwable th) {

System.out.println("in main throwable object caught exception"

+ th.getMessage());

}}}

Output:

Starting of main file name is myfile.ser

caught exceptionmyfile.ser (The system cannot find the file specified)

in main throwable object caught exceptionFile not found

Advertisements

Posted on: March 16, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles