Search This Blog

Saturday 16 August 2014

Defining and throwing Custom Exceptions - JAVA

Defining and throwing Custom Exceptions in Java

In Java you can define and throw your own exceptions by creating your own exception classes.


This program shows how to create and use, define and throw Custom Exceptions in Java.

CustomExceptions.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import CustomExceptions.MyCustomExceptionClass;

public class CustomExceptions {
 public static void main(String args[]){
  FileReader fr = null;
  BufferedReader br = null;
  try {
   fr = new FileReader("myFile.txt");
   br = new BufferedReader(fr);
   String line;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
   if (line != "my Desired output or some other condition")
    throw(new MyCustomExceptionClass());
   
  } catch (MyCustomExceptionClass e) {
   e.getMessage();
  }
    catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  finally{ //close
   System.out.println("Executing finally ...");
   if (fr != null){
    try {
     fr.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
  System.out.println("Still Alive!");
 }
}

MyCustomExceptionClass.java

package CustomExceptions;

public class MyCustomExceptionClass extends Exception {

 /**
  * Every Exception class must have this serialVersionUID.
  * Assuming 45 means some code to me.
  */
 private static final long serialVersionUID = 45; 
 
 @Override
 public String getMessage() {
  return "My Custom Exception Class is printing this message showing the problem";
 }
}

No comments:

Post a Comment