Java-Exception Handling

Exceptions are runtime anomalies that may result in the abnormal termination of the
program.
Exceptions are mainly thrown by system or by a function
---Thrown by system---
ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException
---Thrown by function---
NumberFormatException 
In java all exceptions are classes. Mainly there are two types of exceptions. 
They are:
Exceptions
|
x-- Checked Exceptions: that are trapped by the compiler
|
x-- Unchecked Exceptions: that are not trapped by the compiler
A checked exception must be either reported or caught (handled)
Otherwise the compiler may fail to compile the program.
An unchecked exception may be excepted from handling- it causes failure at runtime only.

---Checked Exceptions---
IOException
SQLException
InterruptedException
SocketException

---Unchecked Exceptions---
ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException

---Hierarchy of Exception classes---
java.lang.Object
|
+-- java.lang.Throwable
|
+-- java.lang.Exception
|
+-- java.lang.RuntimeException

-> Direct or indirect subclasses of class Exception are checked exceptions with an 
exception of class RuntimeException.
-> Direct or indirect subclasses of class RuntimeException are unchecked exceptions.

---UncaughtException.java---
class UncaughtException {
public static void main(String[] args) {
function1(args.length);
System.out.println(
"Program completed normally.");
}
public static void function1(int length) {
int i = 10 / length;
}
}

---CatchingSingleException.java---
class CatchingSingleException {
public static void main(String args[]) {
try {
int i = 10 / args.length;
System.out.println("Still inside the try block.");
} catch(ArithmeticException e) {
System.out.println(
"Arithmetic Exception Handled Successfully.");
System.out.println(e);
System.out.println(e.getMessage());
//e.printStackTrace();
} finally {//optional block
//write statements for releasing all your resources here.
System.out.println("Inside the finally block.");
}

System.out.println("Program terminated normally.");
}
}

---CatchingMultipleExceptions.java---
class CatchingMultipleExceptions {
public static void main(String args[]) {
try {
int i = 10 / args.length;
//assume this to be an unforseen exception
new java.io.FileInputStream("abc.txt");

int[] ar = {10, 20, 30};
ar[50] = 25;
System.out.println("I am still inside the try block.");
} catch(ArithmeticException e) {
System.out.println(e.getMessage());
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array element does not exist.");
} catch(Exception e) {//generic exception handling
try {
e.printStackTrace(new java.io.PrintStream("error.log"));
System.out.println(
"An error occurred. Check the error.log for details.");
} catch (java.io.FileNotFoundException ex) {
System.out.println("Could not create error.log file.");
}
}
System.out.println("Program terminated normally.");
}
}
-----------------------------------------------------------------------------------
class SomeClass {// created by API provider
public void someFunction() throws IllegalAccessException {
//there are lots of statements here and validations follow before
//I throw the exception
throw new IllegalAccessException(
"Security violation."); //checked exception
}
public void setBlahBlah(int value) throws ArithmeticException{
if (value < 0) {
throw new ArithmeticException(
"Negative Number."); //unchecked exception
}
}
}
-----------------------------------------------------------------------------------
class NestedTry {
public static void main(String args[]) {
try { //outer try starts here
int i = 10 / args.length;

//----------------------------Inner Try---------------------------
try {//inner try starts here
int a = 5 / (args.length - 1);
int ar[] = {10, 20};
ar[30] = 50;
} catch(ArrayIndexOutOfBoundsException e) {//inner try catch
System.out.println("Array index out of bounds - Inner Try.");
} finally {
System.out.println("Inside finally - Inner Try.");
}
//---------------------------Inner try ends here-------------------

System.out.println("I am still inside the Outer try block.");
} catch(ArithmeticException e) { //outer try catch
System.out.println("Divide by Zero error - Outer Try.");
} catch(ArrayIndexOutOfBoundsException e) { //outer try catch
System.out.println("Array element does not exist - Outer Try.");
}

System.out.println("Program terminated normally.");
// last statement of the program
}
}
-----------------------------------------------------------------------------------
class SomeClass {// class provided by an API-Provider
public static void someFunction(int i) {
try {// implicit inner try
if (i == 1) {
i /= 0;
} else {
int ar[] = {10, 20};
ar[50] = 10;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array element does not exist - Exception caught in someFunction().");
}
}
}

class NestedTryMethod {// My Class
public static void main(String args[]) {
try {//explicit try
int i = 10 / args.length;
SomeClass.someFunction(args.length);
} catch(ArithmeticException e) {
System.out.println(
"Divide by Zero error - Exception caught in main().");
}

System.out.println("Program terminated normally.");
}
}
-----------------------------------------------------------------------------------
class ThrowCheckedException {// created by developer of the application
public static void main(String args[]) {
try {
new SomeClass().someFunction();
} catch(IllegalAccessException e) {
System.out.println("You do not have necessary privilege to continue this operation.");
}

//new SomeClass().someFunction();
}
}
-----------------------------------------------------------------------------------
class ThrowUncheckedException {// created by an Application Developer
public static void main(String args[]) {
try {
new SomeClass().setBlahBlah(Integer.parseInt(args[0]));
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(
"Please input a non-negative number as command line arg.");
} catch(NumberFormatException excp) {
System.out.println("Please input a integer value.");
} catch(ArithmeticException e) {
System.out.println("Please input a non-negative number.");
System.out.println(e);
System.out.println(e.getMessage());
}
}
}

class SomeClass {// created by API provider
void setBlahBlah(int value) {
if (value < 0) {//validation
throw new ArithmeticException("Negative Number.");
} else {
System.out.println(value +
" is a positive value. I like it!!!");
}
//other statements follow
}
}
-----------------------------------------------------------------------------------
class MyException extends RuntimeException { // created by API provider
MyException() {
}
MyException(String msg) {
super(msg);
}
}

class SomeClass {// created by API provider
public boolean isEvenNo(int x) throws MyException {
if (x < 0) {
throw new MyException(
"Negative value - Invalid.");
} else if (x == 0) {
throw new MyException(
"Zero value - Invalid.");
} else if ((x % 2) != 0) {
throw new MyException(
"Odd Number - Invalid.");
}
return true;
}
}

class UserDefinedException {// created by developer of the application
public static void main(String args[]) {
try {
if (new SomeClass().isEvenNo(
Integer.parseInt(args[0]))) {
//may raise a exception called as MyException
System.out.println(
"The no " + args[0] +
" is a even number.");
}
} catch(MyException e) {
System.out.println(e);
System.out.println(e.getMessage());
System.out.println("----------------------------------------------------");
}
}
 

Post a Comment

0 Comments