Lecture 19-20 (Exceptions in Java)
Lecture 19-20 (Exceptions in Java)
Whats Exception
An exception is an abnormal condition that occurs at run time. For example divide by 0. During execution of a statement within any method if any exceptional condition occurs the Java Runtime Environment (JRE) i.e. java interpreter creates a suitable Exception object and throws it. Every Exception is basically an object belonging to Javas Exception class Hierarchy. Exceptions needs to be handled so that appropriate actions can be taken. Programmer can also provide exception handling code. However if there is no exception handling code present during runtime and exception occurs, then java interpreter provides default exception handler. Default Exception Handler displays the name of the exception object in string form and stops the execution of the program. However , programmer can provide exception handling code and programs execution can continue even after the occurrence of exception.
Types of Exceptions
All Exceptions that extend the RuntimeException or any one of its subclass are unchecked exceptions
A. Unchecked Exceptions
Whether you catch the exception or not compiler will pass the compilation process.
If Unchecked exception is caught then exception handling code will be executed and programs execution continues.
If Unchecked exception is not caught then java interpreter will provide the default handler. But in this case execution of the program will be stopped by displaying the name of the exceptions object.
Unchecked Exceptions
Some Common Unchecked Exceptions 1. ArithmaticException (Divide By 0) 2. ArrayIndexOutOfBoundsException 3. ArrayStoreException 4. FileNotFoundException 5. NullPointerException 6. NumberFormatException 7. IllegalArumentsException
Throwable
Exception
Error
RunTimeException
UncheckedExceptions Example
class Exceptiondemo1 { public static void main(String arhs[]) throws ArithmeticException { int a=10; int b= 5; int c =5; No Need to mention for int x = a/(b-c); // Dynamic Initilization Unchecked Exceptions System.out.println("c="+c); int y = a/(b+c); System.out.println("y="+y); Can Throw an Exception } } D:\java\bin>javac Exceptiondemo1.java << Compilation Step Pass>> D:\java\bin>java Exceptiondemo1 Exception in thread "main" java.lang.ArithmeticException: / by zero at Exceptiondemo1.main(Exceptiondemo1.java:8)
Cont
class extest { public static void main(String args[]) {
Types of Exceptions
B Checked Exceptions All Exceptions that extends the Exception or any one its subclass except RunTimeException class are checked exceptions Checked Exceptions are checked by the Java compiler. There are two approaches that a user can follow to deal with checked exceptions
If Checked exception is not caught then java interpreter will provide the default handler. But in this case execution of the program will be stopped by displaying the name of the exceptions object.
Throwable
Exception
Error
EXCEPT
RuntimeException
import java.io.*; WILL THIS CODE class Exceptiondemo3 COMPILE { public static void main(String args[]) SUCCESSFULLY { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
1. throws clause is used with methods to indicate type of Exception a method can throw 2. Specifically required for Checked Exceptions [ To Pass Compilation process]. It can/may be used for unchecked exceptions also. 3. A method can throw as many exceptions.
cont.
Method 2 << Put the statements in try catch block and catch >> import java.io.*; class Exceptiondemo3 { public static void main(String args[]) {
BufferedReader br = new BufferedReader(new inputStreamReader(System.in));
Exception Handling
Exception Handling Requires the Following four steps 1. Finding the problem (Identify the statements whose execution may result in Exception. Put all those statements in a try{..} block) 2. Inform that an exception is thrown (Throw the Exception) << Note Down throw vs throws>> 3. Receive the exception ( Catch the exception using catch{..} block) 4. Provide exception handling code in catch block.
class Exceptiondemo1 { public static void main(String arhs[]) { int a=10; int b= 5; int c =5; try { int x = a/(b-c); System.out.println("c="+c); D:\java\bin>java Exceptiondemo1 } java.lang.ArithmeticException: / by zero catch(ArithmeticException e) y=1 { System.out.println(e.toString()); } int y = a/(b+c); System.out.println("y="+y); } }
Catching an Exception
{ int a[]= {5,10}; try { int b= Integer.parseInt(args[0]); int x = a[b]/(b-a[1]); catch(ArithmeticException e) System.out.println("x="+x); { System.out.println(e.toString()); }
} catch(NumberFormatException e) { System.out.println(e.toString()); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e.toString()); }
This Statement is outside catch block and will be executed in any case
System.out.println("Hello This is Exception Test"); } // End of main() method }// End of class Exceptiondemo4
OUTPUT
What will be o/p if you execute it like 1. Java Exceptiondemo4 2. java Exceptiondemo4 1 3. 3. java exceptiondemo4 oop NO COMMAND LINE ARGUMENTS COMMAND LINE ARGUMENTS PASSED AS 1 COMMAND LINE ARGUMENT PASSED oop
. } . } } }
. . . .
} } } }
{ {
. .
} }
} } } }
catch(ArithmeticException e) { System.out.println("Exception : "+ e.toString()); System.out.println("By Inner try"); } } // End of outer try
// Catch Blocks for outer try catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception : "+ e.toString()); System.out.println("By Outr try"); } catch(NumberFormatException e) { System.out.println("Exception : "+ e.toString()); System.out.println("By Outer try"); } } // End of main } // End of class
To make a Unchecked exception , make your exception class a subclass of RunTimeException OR any one of its subclass .
class class class class XException YException ZException ZException extends extends extends extends RunTimeException { } AritmeticException { } ArrayIndexOutOfException { } IndexOutOfBoundsException { }
EXAMPLE 1: class InvalidBOXException extends RuntimeException { InvalidBOXException(String msg) { super(msg); System.out.println("An attempt is made to create an Invalid BOx object "); } } class BOX Optional as InvalidBOXException { is Unchecked private double length; private double width; private double height; BOX(double l, double w, double h) throws InvalidBOXException { if( l <=0 || w <= 0 || h <= 0) throw new InvalidBOXException("Invalid BOX Object creation"); length = l; width = w; height = h; }
double getLength() { return length; } double getWidth() { return width; } double getHeight() { return height; } double Area() { return 2*(length*width + width*height + height*length); } double Volume() { return length*width*height ; } } class exceptiontest1 { public static void main(String args[]) {
System.out.println(Area of b2:+b2.Area()); } }
D:\java\bin>java exceptiontest1 An attempt is made to create an Invalid BOx object Exception in thread "main" InvalidBOXException: Inavlid BOX Object creation at BOX.<init>(exceptiontest1.java:18) at exceptiontest1.main(exceptiontest1.java:35)
<RUNTIME Error> D:\java\bin>java exceptiontest1 Exception in thread "main" java.lang.NullPointerException at exceptiontest1.main(exceptiontest1.java: 36)
Checked Exceptions
Make your exception class extends Exception class or any one of its subclass except RumtimeException. Checked Exceptions needs to either caught or informed by use of throws clause Note down that throw clause is used to throw the exception where as throws clause is used to inform that an exception is thrown by the method. Throw clause is used inside method body where as throws clause is used with first line of the method. Throws clause can be used to inform both type of exceptions. But in case a method is throwing a unchecked exception then it is not compulsory to inform. In case a method is throwing a checked Exception, then it has either to caught the exception or informs by using throws clause or it can do both.
EXAMPLE 1: class InvalidBOXException extends Exception Checked { Exception InvalidBOXException(String msg) { super(msg); System.out.println("An attempt is made to create an Invalid BOx object "); } } class BOX { Any Method or constructor which throws an private double length; checked Type Exception must inform it thru private double width; throws clause private double height; BOX(double l, double w, double h) { if( l <=0 || w <= 0 || h <= 0) throw new InvalidBOXException("Inavlid BOX Object creation"); length = l; width = w; height = h; }
double getLength() { return length; } double getWidth() { return width; } double getHeight() { return height; } double Area() { return 2*(length*width + width*height + height*length); } double Volume() { return length*width*height ; } } class exceptiontest1 { public static void main(String args[]) { BOX b1 = new BOX(0,0,0); BOX b2 = new BOX(10,4,5); System.out.println(Area of b2:+b2.Area()); } }
D:\java\bin>javac exceptiontest1.java < Compile Time Error> exceptiontest1.java:18: unreported exception InvalidBOXException; must be caught or declared to be thrown throw new InvalidBOXException("Inavlid BOX Object creation"); ^ 1 error
EXAMPLE 1: class InvalidBOXException extends Exception { InvalidBOXException(String msg) { super(msg); System.out.println("An attempt is made to create an Invalid BOx object "); } }
class BOX { private double length; private double width; private double height; BOX(double l, double w, double h) throws InvalidBOXException { if( l <=0 || w <= 0 || h <= 0) throw new InvalidBOXException("Inavlid BOX Object creation"); length = l; width = w; height = h; }
double getLength() { return length; } double getWidth() { return width; } double getHeight() { return height; } double Area() { return 2*(length*width + width*height + height*length); } double Volume() { return length*width*height ; } } class exceptiontest1 { public static void main(String args[]) throws InvalidBOXException { BOX b1 = new BOX(0,0,0); BOX b2 = new BOX(10,4,5); System.out.println(Area of b2:+b2.Area()); } }
D:\java\bin>java exceptiontest1 An attempt is made to create an Invalid BOx object Exception in thread "main" InvalidBOXException: Inavlid BOX Object creation at BOX.<init>(exceptiontest1.java:18) at exceptiontest1.main(exceptiontest1.java:36)
Example(finally clause)
class ex10 { public static void main(String args[]) { int a=10; int b = 20; try { int b1=Integer.parseInt(args[0]); int x = a/(a-b1); try { int y = b/(b-b1); } finally { System.out.println("Inner Block executed"); finally } { } System.out.println("Outer Block executed"); } } }
Output
D:\java\bin>java ex10 Outer Block executed Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at ex10.main(ex10.java:9) D:\java\bin>java ex10 45 Inner Block executed Outer Block executed D:\java\bin>java ex10 10 Outer Block executed Exception in thread "main" java.lang.ArithmeticException: / by zero at ex10.main(ex10.java:10) D:\java\bin>java ex10 20 Inner Block executed Outer Block executed Exception in thread "main" java.lang.ArithmeticException: / by zero at ex10.main(ex10.java:13)
InvalidIdNoYearException
InvalidIdNoDesciplineException
Example
class AException extends RuntimeException{} class BException extends AException{} class CException extends AException{}
AException
class ex11 BException CException { public static void main(String args[]) Catch sub class Exceptions First then { super class Exceptions try { int a=10; D:\java\bin>javac ex11.java } ex11.java:14: exception BException has already been caught catch(AException e) {} catch(BException e) {} catch(BException e) {} ^ catch(CException e) {} ex11.java:15: exception CException has already been caught } catch(CException e) {} } ^ 2 errors
Exception Example
class Student { private String name; private String idno;
Exception StudentException
InvalidName Exception
InvalidId Exception
InvalidYear Exception
InvalidNumber Exception
class InvalidYearException extends StudentException { InvalidYearException(String msg) { super(msg); System.out.println(msg); } } class InvalidNumberException extends StudentException { InvalidNumberException(String msg) { super(msg); System.out.println(msg); } }
class Student { private String name; private String idno; private boolean containsAlphabetsOnly(String str) { for(int i=0;i<str.length();i++) { int j = str.charAt(i); if(j < 65) return false; if(j > 125) return false; if(j > 91 && j < 96) return false; } return true; }
Student(String name,String idno) throws StudentException { if(!containsAlphabetsOnly(name)) throw new InvalidNameException("Invalid Name"); int a = Integer.parseInt(idno.substring(0,4)); if( a < 1995 || a > 2007) throw new InvalidYearException("Invalid Id Year"); int b = Integer.parseInt(idno.substring(8)); if( b <= 0 || b > 999) throw new InvalidNumberException("Invalid Student Number");
class exceptiontest { public static void main(String args[]) throws StudentException { Student std1 = new Student("123","sttts"); } }
E:\oop>java studentexception Exception in thread "main" java.lang.NoClassDefFoundError: studentexception (wrong name: StudentException)at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source)at java.net.URLClassLoader.defineClass(Unknown Source)
Sample Example 1
class Sample { public static void main(String args[]) { try { int a = 10; } catch(Exception e) {} } // End of main() }//End of class Sample
NO ERROR
Example 2
import java.io.*; class Sample { public static void main(String args[]) { try { int a = 10; Sample.java:10: exception } java.io.IOException is never thrown in body catch(IOException e) {} of corresponding try statement catch(IOException e) {} }// End of main() ^ }//End of class sample 1 error
Example 3
import java.io.*; class Sample { public static void main(String args[]) { try { int a = 10; } catch(Exception e) {} catch(RuntimeException e) {} } D:\java\bin>javac Sample.java }//End of class Sample.java:11: exception java.lang.RuntimeException has already been caught catch(RuntimeException e) {} ^ 1 error
Example 4
class ExceptionDemo4 { public static void main(String args[]) throws Exception { int a= 10; int b = a + 10; System.out.println("a="+a+"b="+b); } }
Example 5
class ExceptionDemo4 { public static void main(String args[]) throws RuntimeException { int a= 10; int b = a + 10; System.out.println("a="+a+"b="+b); } }
Example 6
import java.io.*; class ExceptionDemo4 { public static void main(String args[]) throws IOException { int a= 10; int b = a + 10; System.out.println("a="+a+"b="+b); } }
Example 7
class A { public void display() throws Exception { System.out.println("Hello"); }// End of display() display() method is overridden in sub class B. }// End of class A
As display throws Exception
class B extends A Bs display throws RuntimeException { public void display() throws RuntimeException { System.out.println("Hi"); }// End of display() NO ERROR IN CODE. }// End of class B
COMPILES SUCESSFULLY
Example 8
class A { public void display() throws RuntimeException { System.out.println("Hello"); display() method is overridden in sub class B. }// End of display() As display throws RuntimeException }// End of class A
Bs display throws Exception
class B extends A { public void display() throws Exception { System.out.println("Hi"); }// End of display() }// End of class B
E:\Java Programs>javac AB.java AB.java:10: display() in B cannot override display() in A; overridden method does not throw java.lang.Exception public void display() throws Exception ^ 1 error
Example 9
import java.io.*; class A { public void display() throws RuntimeException { display() method System.out.println("Hello"); is overridden in }// End of display() sub class B }// End of class A class B extends A { public void display() throws IOException { E:\Java Programs>javac AB.java System.out.println("Hi"); AB.java:10: display() in B cannot override }// End of display() display() in A; overridden method does not }// End of class B throw java.io.IOException
public void display() throws IOException
Example 10
import java.io.*; class A { public void display() throws IOException { System.out.println("Hello"); }// End of display() }// End of class A
class B extends A { public void display() throws RuntimeException { System.out.println("Hi"); }// End of display() NO ERROR IN CODE. }// End of class B
COMPILES SUCESSFULLY