What is an Exception?

Some Exceptional event or error that occurs during runtime. It causes normal program flow to be disrupted. For example, divide by zero is an exception. Some other common exceptions are accessing the elements of an array beyond its range, invalid input, hard disk crash, opening a non-existent file, heap memory exhausted.

An exception in Java is an object that is created when an abnormal situation arises in your program. This object has members that stores information about the nature of the problem. An Exception is always an object of some subclass of the standard class Throwable. Java provides a very well defined hierarchy of Exceptions to deal with situations which are unusual. All Standard exceptions are covered by two direct subclasses of the class Throwable:

  • Class Error
  • Class Exception

Error Class

Used by the Java run-time system to handle errors occurring in the run-time environment. Generally it is beyond the control of user programs.

Examples

  • Out of memory errors
  • Hard disk crash

Exception class

Conditions that user programs can reasonably deal with. Usually the result of some flaws in the user program code.

Examples

  • Division by zero error
  • Array out-of-bounds error

Checked Exceptions vs. Unchecked Exceptions

Exceptions can be classified into two main categories: Checked Exceptions and Unchecked Exception.

Checked Exceptions:

Checked Exceptions represent invalid conditions in areas outside the immediate control of the program. For example, invalid user input, database problems, network outages, absent files. These are subclasses of Exception

Unchecked Exceptions:

Unchecked Exceptions represent defects in the program (bugs) – often invalid arguments passed to a non-private method. According to Java founder J. Gosling: “Unchecked runtime exceptions represent conditions that reflect errors in your program’s logic and cannot be reasonably recovered from at run time.” These are are subclasses of RuntimeException. In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example,

  • NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it.
  • an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array.

These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.

Example

class DivByZero {
public static void main(String args[]) {
System.out.println(3/0);
System.out.println(“Pls. print me.”);
}

After compiling and running we get:

Exception in thread "main“ java.lang.ArithmeticException: \ by zero at 
DivByZero.main(DivByZero.java:3)

What Happens When an Exception Occurs?

When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system. Creating an exception object and handing it to the runtime system is called “throwing an exception”. Exception object contains information about the error, including its type and the state of the program when the error occurred.

Dealing With Exceptions

For all subclasses of Exception Class (except RuntimeException) you must include code to deal with them. If your program has the potential to generate an exception of such a type, you have got two choices.

  • Handle the exception within the method
  • Register that your method may throw such an exception (You are passing the exception on)

If you do neither your code won’t compile

Catching Exceptions: The try-catch Statements

Syntax:

try {
    <code to be monitored for exceptions>
}
catch (<ExceptionType1> <ObjName>) {
    <handler if ExceptionType1 occurs>…
}
 catch (<ExceptionTypeN> <ObjName>) {
    <handler if ExceptionTypeN occurs>…
}

Example-1

class DivByZero {
 public static void main(String args[]) {
 try {
	System.out.println(3/0);
	System.out.println(“Please print me.”);
 }
 catch (ArithmeticException exc) {
	//Division by zero is an ArithmeticException
	 System.out.println(exc);
}
System.out.println(“After exception.”);
}

Example-2

class MultipleCatch {
public static void main(String args[]) {
	try {
		int den = Integer.parseInt(args[0]);
		System.out.println(3/den);
		}
	catch (ArithmeticException exc) {
		System.out.println(“Divisor was 0.”);
	}
	catch (ArrayIndexOutOfBoundsException exc2) {
		System.out.println(“Missing argument.”);
	}
 	System.out.println(“After exception.”);
}
}

Nested Try

class NestedTryDemo {
public static void main(String args[]){
try {
	int a = Integer.parseInt(args[0]);
	try {
		int b = Integer.parseInt(args[1]);
		System.out.println(a/b);
	} catch (ArithmeticException e) {
		System.out.println(“Div by zero error!");
	}
	}
 catch (ArrayIndexOutOfBoundsException) {
	System.out.println(“Need 2 parameters!");
}
}}

Nested try’s with methods

class NestedTryDemo2 {
	static void nestedTry(String args[]) {
	try {
		 int a = Integer.parseInt(args[0]);
		 int b = Integer.parseInt(args[1]);
		 System.out.println(a/b);
	 } catch (ArithmeticException e) {
		 System.out.println("Div by zero error!");
	}}
 public static void main(String args[]){
	try {
		nestedTry(args);
	 } catch (ArrayIndexOutOfBoundsException e) {
		System.out.println("Need 2 parameters!");
	}
}}

Using Finally Keyword

Block of code is always executed despite of different scenarios:

  • Forced exit occurs using a return, a continue or a break statement
  • Normal completion
  • Caught exception thrown
  • Uncaught exception thrown
  • Exception thrown was not specified in any catch block in the method

Syntax:

try {
    <code to be monitored for exceptions>
}
 catch (<ExceptionType1> <ObjName>) {
    <handler if ExceptionType1 occurs>
}
finally {
    <code to be executed before the try block ends>
}

Example

class FinallyDemo {
static void myMethod(int n) throws Exception{
	try {
	switch(n) {
	case 1: System.out.println("1st case");
		return;
	case 3: System.out.println("3rd case");
		throw new RuntimeException("3!");
	 case 4: System.out.println("4th case");
		throw new Exception("4!");
	 case 2: System.out.println("2nd case");
	}
	} catch (RuntimeException e) {
		System.out.print("RuntimeException: ");
		System.out.println(e.getMessage());
	}
finally{System.out.println("in finally try blk entered");}
System.out.println("after finally");
}
public static void main(String args[]){
	 for (int i=1; i<=4; i++) {
	try {
		FinallyDemo.myMethod(i);
	}
	catch (Exception e){

	System.out.print("Exception caught: ");
	System.out.println(e.getMessage());
	}
	System.out.println();
}
}
}

Example

public static void main(String args[]){
	 for (int i=1; i<=4; i++) {
	try {
		FinallyDemo.myMethod(i);
	}
	catch (Exception e){
		System.out.print("Exception caught: ");
		System.out.println(e.getMessage());
	}
	System.out.println();
}
}
Tagged with: ClassesJAVAObject Oriented
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.