Skip to content

Instantly share code, notes, and snippets.

@tgvdinesh
Created February 5, 2017 09:02
Show Gist options
  • Save tgvdinesh/d98108c7b0481cb1b93ffb72491155e9 to your computer and use it in GitHub Desktop.
Save tgvdinesh/d98108c7b0481cb1b93ffb72491155e9 to your computer and use it in GitHub Desktop.
Exception handling in Java 1.6
package com.example.java;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Exception handling
* <a href="http://www.journaldev.com/1696/exception-handling-in-java">Exception Handling in Java</a>
*/
class ExceptionHandling {
public static void main(String[] args) throws MyException {
try {
processFile("file.txt");
} catch (MyException e) {
processErrorCodes(e);
}
}
private static void processErrorCodes(MyException e) throws MyException {
switch (e.getErrorCode()) {
case "BAD_FILE_TYPE":
System.out.println("Bad File Type, notify user");
throw e;
case "FILE_NOT_FOUND_EXCEPTION":
System.out.println("File Not Found, notify user");
throw e;
case "FILE_CLOSE_EXCEPTION":
System.out.println("File Close failed, just log it.");
break;
default:
System.out.println("Unknown exception occurred, lets log it for further debugging." + e.getMessage());
e.printStackTrace();
}
}
private static void processFile(String file) throws MyException {
InputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new MyException(e.getMessage(), "FILE_NOT_FOUND_EXCEPTION");
} finally {
try {
if (fis != null) fis.close();
} catch (IOException e) {
throw new MyException(e.getMessage(), "FILE_CLOSE_EXCEPTION");
}
}
}
}
class MyException extends Exception {
private static final long serialVersionUID = 4664456874499611218L;
private String errorCode = "Unknown_Exception";
MyException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
String getErrorCode() {
return this.errorCode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment