Home Tutorial Java Core Exception Using throw keyword in exception handling in Core Java

 
 

Share on Google+Share on Google+
Using throw keyword in exception handling in Core Java
Posted on: March 16, 2010 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Using throw keyword in exception handling in Core Java:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 16, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com