ExceptionsDhrubojyotiKayal
Guarded sectionA block where you think some exceptional things – problem with data base connection, network failure, missing data – may happentry{	//code}try block
The thrown exception must end up someplace – exception handlerException handlers immediately follow the try block and are denoted by the keyword catch	try { 	// Code that might generate exceptions 	} catch(Type1 id1)|{ 	// Handle exceptions of Type1 	} catch(Type2 id2) { 	// Handle exceptions of Type2 	} catch(Type3 id3) { 	// Handle exceptions of Type3 } Exception Handler
If an exception is thrown, the exception-handling mechanism goes hunting for the first handler with an argument that matches the type of the exception Then it enters that catch clause, and the exception is considered handled The search for handlers stops once the catch clause is finished. Only the matching catch clause executes (unlike switch – no need for break or default)Sometimes one handler can be sufficient.Catch block
To create your own exception class, you must inherit from an existing exception class, preferably one that is close in meaning to your new exception class SimpleException extends Exception {} Creating your own exceptions
public class InheritingExceptions { public void f() throws SimpleException { System.out.println("Throw SimpleException from f()"); throw new SimpleException(); } public static void main(String[] args) { InheritingExceptionssed = new InheritingExceptions(); try { sed.f(); } catch(SimpleException e) { System.out.println("Caught it!"); e.printStackTrace(); } } } printStackTrace – shows sequence of methods called and where exactly in execution the exception was raised making it easier to pin point exception source.Using your own exception
In Java, you’re encouraged to inform the client programmer, who calls your method, of the exceptions that might be thrown from your method This is civilized, because the caller can then know exactly what code to write to catch all potential exceptions Add throws followed by Exception names to tell the world the problems your code may causeThrowing Exceptions
void f() throws TooBig, TooSmall, DivZero { //... void f() { //... This is not safe and can be vulnerable to RuntimeException and its likesThrowing Exceptions
It is possible to create a handler that catches any type of exception by catching the base-class exception type Exceptioncatch(Exception e) { System.out.println("Caught an exception"); } Since the Exception class is the base of all the exception classes that are important to the programmer, you don’t get much specific information about the exception, but you can call the methods that come from its base type ThrowableString getMessage( ) String getLocalizedMessage( ) void printStackTrace( ) void printStackTrace(PrintStream) void printStackTrace(java.io.PrintWriter)Catching any Exception
Write a Java code which first has an exception handler for Exception class followed by another exception handler for custom MyClassExcercise
The Java class Throwable describes anything that can be thrown as an exception Error represents compile-time and system errors that you don’t worry about catching Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and runtime accidents. So the Java programmer’s base type of interest is usually Exception. This are called checked exceptionsStandard Java Exceptions
RuntimeException and its children have special meaning to the runtime. They cause hazards without intimation – you do not declare them in the method exception specificationThey generally results of programming errorsUse runtime exception if a you cannot recover from an operationIf you are handling/catching RuntimeException there is problem in your code and designUnchecked Exceptions
public class NeverCaught { static void f() { throw new RuntimeException("From f()"); } static void g() { f(); } public static void main(String[] args) { g(); } } RuntimeException in Action
There’s often some piece of code that you want to execute whether or not an exception is thrown within a try block To achieve this effect, you use a finally clause at the end of all the exception handlers try { // The guarded region: Dangerous activities // that might throw A, B, or C } catch(A a1) { // Handler for situation A } catch(B b1) { // Handler for situation B } catch(C c1) { // Handler for situation C } finally { // Activities that happen every time } And finally
class ThreeException extends Exception {} public class FinallyWorks { 	static int count = 0; 	public static void main(String[] args) { 	while(true) { try { // Post-increment is zero first time: if(count++ == 0) throw new ThreeException(); System.out.println("No exception"); } catch(ThreeException e) { System.out.println("ThreeException"); } finally { System.out.println("In finally clause"); if(count == 2) break; // out of "while" } } } Finally in Action
public class MultipleReturns { 	public static void f(inti) { 		print("Initialization that requires cleanup"); 		try { 			print("Point 1"); 			if(i== 1) return; 			print("Point 2"); 			if(i== 2) return; 			print("Point 3"); 			if(i== 3) return; 			print("End"); 			return; 		}finally { 		print("Performing cleanup"); 		} 	} 	public static void main(String[] args) { 		for(int i = 1; i <= 4; i++) 		f(i); 	} } finally and return
Q&A

17 exceptions

  • 1.
  • 2.
    Guarded sectionA blockwhere you think some exceptional things – problem with data base connection, network failure, missing data – may happentry{ //code}try block
  • 3.
    The thrown exceptionmust end up someplace – exception handlerException handlers immediately follow the try block and are denoted by the keyword catch try { // Code that might generate exceptions } catch(Type1 id1)|{ // Handle exceptions of Type1 } catch(Type2 id2) { // Handle exceptions of Type2 } catch(Type3 id3) { // Handle exceptions of Type3 } Exception Handler
  • 4.
    If an exceptionis thrown, the exception-handling mechanism goes hunting for the first handler with an argument that matches the type of the exception Then it enters that catch clause, and the exception is considered handled The search for handlers stops once the catch clause is finished. Only the matching catch clause executes (unlike switch – no need for break or default)Sometimes one handler can be sufficient.Catch block
  • 5.
    To create yourown exception class, you must inherit from an existing exception class, preferably one that is close in meaning to your new exception class SimpleException extends Exception {} Creating your own exceptions
  • 6.
    public class InheritingExceptions{ public void f() throws SimpleException { System.out.println("Throw SimpleException from f()"); throw new SimpleException(); } public static void main(String[] args) { InheritingExceptionssed = new InheritingExceptions(); try { sed.f(); } catch(SimpleException e) { System.out.println("Caught it!"); e.printStackTrace(); } } } printStackTrace – shows sequence of methods called and where exactly in execution the exception was raised making it easier to pin point exception source.Using your own exception
  • 7.
    In Java, you’reencouraged to inform the client programmer, who calls your method, of the exceptions that might be thrown from your method This is civilized, because the caller can then know exactly what code to write to catch all potential exceptions Add throws followed by Exception names to tell the world the problems your code may causeThrowing Exceptions
  • 8.
    void f() throwsTooBig, TooSmall, DivZero { //... void f() { //... This is not safe and can be vulnerable to RuntimeException and its likesThrowing Exceptions
  • 9.
    It is possibleto create a handler that catches any type of exception by catching the base-class exception type Exceptioncatch(Exception e) { System.out.println("Caught an exception"); } Since the Exception class is the base of all the exception classes that are important to the programmer, you don’t get much specific information about the exception, but you can call the methods that come from its base type ThrowableString getMessage( ) String getLocalizedMessage( ) void printStackTrace( ) void printStackTrace(PrintStream) void printStackTrace(java.io.PrintWriter)Catching any Exception
  • 10.
    Write a Javacode which first has an exception handler for Exception class followed by another exception handler for custom MyClassExcercise
  • 11.
    The Java classThrowable describes anything that can be thrown as an exception Error represents compile-time and system errors that you don’t worry about catching Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and runtime accidents. So the Java programmer’s base type of interest is usually Exception. This are called checked exceptionsStandard Java Exceptions
  • 12.
    RuntimeException and itschildren have special meaning to the runtime. They cause hazards without intimation – you do not declare them in the method exception specificationThey generally results of programming errorsUse runtime exception if a you cannot recover from an operationIf you are handling/catching RuntimeException there is problem in your code and designUnchecked Exceptions
  • 13.
    public class NeverCaught{ static void f() { throw new RuntimeException("From f()"); } static void g() { f(); } public static void main(String[] args) { g(); } } RuntimeException in Action
  • 14.
    There’s often somepiece of code that you want to execute whether or not an exception is thrown within a try block To achieve this effect, you use a finally clause at the end of all the exception handlers try { // The guarded region: Dangerous activities // that might throw A, B, or C } catch(A a1) { // Handler for situation A } catch(B b1) { // Handler for situation B } catch(C c1) { // Handler for situation C } finally { // Activities that happen every time } And finally
  • 15.
    class ThreeException extendsException {} public class FinallyWorks { static int count = 0; public static void main(String[] args) { while(true) { try { // Post-increment is zero first time: if(count++ == 0) throw new ThreeException(); System.out.println("No exception"); } catch(ThreeException e) { System.out.println("ThreeException"); } finally { System.out.println("In finally clause"); if(count == 2) break; // out of "while" } } } Finally in Action
  • 16.
    public class MultipleReturns{ public static void f(inti) { print("Initialization that requires cleanup"); try { print("Point 1"); if(i== 1) return; print("Point 2"); if(i== 2) return; print("Point 3"); if(i== 3) return; print("End"); return; }finally { print("Performing cleanup"); } } public static void main(String[] args) { for(int i = 1; i <= 4; i++) f(i); } } finally and return
  • 17.