What is an Exception?

? Exceptional event - typically an error that occurs during runtime
? Cause normal program flow to be disrupted
? Examples
– Divide by zero errors
– Accessing the elements of an array beyond its range
– Invalid input
– Hard disk crash
– Opening a non-existent file
– Heap memory exhausted

Exception Example


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


Example: Default Exception Handling

? Displays this error message

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

? Default exception handler
– Provided by Java runtime
– Prints out exception description
– Prints the stack trace
? Hierarchy of methods where the exception occurred
– Causes the program to terminate



Catching Exceptions with try-catch


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>
}


The try-catch Statements

1 class DivByZero {
2 public static void main(String args[]) {
3 try {
4 System.out.println(3/0);
5 System.out.println(“Please print me.”);
6 } catch (ArithmeticException exc) {
7 //Division by zero is an ArithmeticException
8 System.out.println(exc);
9 }
10 System.out.println(“After exception.”);
11 }
12 }






Catching Exceptions: Nested try's

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!");
}
}
}


Catching Exceptions with finally


Catching Exceptions:

The finally Keyword

? 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>
}

? Contains the code for cleaning up after a try or a
catch






? 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
? Exception was thrown and caught in the method
– Uncaught exception thrown
? Exception thrown was not specified in any catch block in the method



Throwing Exceptions


Throwing Exceptions: The throw Keyword

? Java allows you to throw exceptions (generate exceptions)
throw <exception object>;
? An exception you throw is an object
– You have to create an exception object in the same way you create any other object
? Example:
throw new ArithmeticException(“testing...”);



Example: Throwing Exceptions

1 class ThrowDemo {
2 public static void main(String args[]){
3 String input = “invalid input”;
4 try {
5 if (input.equals(“invalid input”)) {
6 throw new RuntimeException("throw demo");
7 } else {
8 System.out.println(input);
9 }
10 System.out.println("After throwing");
11 } catch (RuntimeException e) {
12 System.out.println("Exception caught:" + e);
13 }
14 }
15 }


Rules in Exception Handling


? A method is required to either catch or list all exceptions it might throw
– Except for Error or RuntimeException, or their subclasses
? If a method may cause an exception to occur but does not catch it, then it must say so using the throws keyword
– Applies to checked exceptions only
? Syntax:

<type> <methodName> (<parameterList>)
throws <exceptionList> {
<methodBody>
}


Example: Method throwing an Exception

1 class ThrowingClass {
2 static void meth() throws ClassNotFoundException {
3 throw new ClassNotFoundException ("demo");
4 }
5 }
6 class ThrowsDemo {
7 public static void main(String args[]) {
8 try {
9 ThrowingClass.meth();
10 } catch (ClassNotFoundException e) {
11 System.out.println(e);
12 }
13 }
14 }


Exception Class Hierarchy


The Error and Exception Classes

? Throwable class
– Root class of exception classes
– Immediate subclasses
? Error
? Exception
? 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


? Error class
– Used by the Java run-time system to handle errors occurring in the run-time environment
– Generally beyond the control of user programs
– Examples
? Out of memory errors
? Hard disk crash

Exception Classes and Hierarchy






? Multiple catches should be ordered from subclass to superclass.


1 class MultipleCatchError {
2 public static void main(String args[]){
3 try {
4 int a = Integer.parseInt(args [0]);
5 int b = Integer.parseInt(args [1]);
6 System.out.println(a/b);
– } catch (ArrayIndexOutOfBoundsException e) {
– } catch (Exception ex) {
1 }
2 }
3 }



Checked Exceptions & Unchecked Exceptions



? Checked exception
– Java compiler checks if the program either catches or lists the occurring checked exception
– If not, compiler error will occur
? Unchecked exceptions
– Not subject to compile-time checking for exception handling
– Built-in unchecked exception classes
? Error
? RuntimeException
? Their subclasses
– Handling all these exceptions may make the program cluttered and may become a nuisance



Creating Your Own Exception Class



? Steps to follow
– Create a class that extends the RuntimeException or the Exception class
– Customize the class
? Members and constructors may be added to the class
? Example:


1 class HateStringExp extends RuntimeException {
2 /* some code */
3 }








How To Use Your Own Exceptions

1 class TestHateString {
2 public static void main(String args[]) {
3 String input = "invalid input";
4 try {
5 if (input.equals("invalid input")) {
6 throw new HateStringExp();
7 }
8 System.out.println("Accept string.");
9 } catch (HateStringExp e) {
10 System.out.println("Hate string!”);
11 }
12 }
13 }

Assertions


What are Assertions?

? Allow the programmer to find out if the program behaves as expected
? Informs the person reading the code that a particular condition should always be satisfied
– Running the program informs you if assertions made are true or not
– If an assertion is not true, an AssertionError is thrown
? User has the option to turn it off or on when running the application


Enabling or Disabling Assertions

? Program with assertions may not work properly if used by clients not aware that assertions were used in the code
? Compiling

– With assertion feature:
javac –source 1.4 MyProgram.java
– Without the assertion feature:
javac MyProgram.java
? Enabling assertions:
– Use the –enableassertions or –ea switch.
java –enableassertions MyProgram


Assert Syntax

? Two forms:
– Simpler form:
assert <expression1>;
where
? <expression1> is the condition asserted to be true
– Other form:
assert <expression1> : <expression2>;
where
? <expression1> is the condition asserted to be true
? <expression2> is some information helpful in diagnosing why the statement failed


Assert Syntax

1 class AgeAssert {
2 public static void main(String args[]) {
3 int age = Integer.parseInt(args[0]);
4 assert(age>0);
5 /* if age is valid (i.e., age>0) */
6 if (age >= 18) {
7 System.out.println(“You're an adult! =)”);
8 }
9 }
10 }

Leave a Reply

Subscribe to Posts | Subscribe to Comments

About This Site

Howdy! My name is Suersh Rohan and I am the developer and maintainer of this blog. It mainly consists of my thoughts and opinions on the technologies I learn,use and develop with.

Blog Archive

Powered by Blogger.

- Copyright © My Code Snapshots -Metrominimalist- Powered by Blogger - Designed by Suresh Rohan -