SlideShare una empresa de Scribd logo
1 de 17
Exceptions DhrubojyotiKayal
Guarded section A block where you think some exceptional things – problem with data base connection, network failure, missing data – may happen try{ 	//code } try block
The thrown exception must end up someplace – exception handler Exception 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 cause Throwing Exceptions
void f() throws TooBig, TooSmall, DivZero { //...  void f() { //...  This is not safe and can be vulnerable to RuntimeException and its likes Throwing Exceptions
It is possible to create a handler that catches any type of exception by catching the base-class exception type Exception catch(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 Throwable String 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 MyClass Excercise
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 exceptions Standard 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 specification They generally results of programming errors Use runtime exception if a you cannot recover from an operation If you are handling/catching RuntimeException there is problem in your code and design Unchecked 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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling
Exception handlingException handling
Exception handling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
exception handling
exception handlingexception handling
exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 

Destacado

Destacado (18)

02 what is java
02   what is java02   what is java
02 what is java
 
SecRBAC: Secure data in the Clouds
SecRBAC: Secure data in the CloudsSecRBAC: Secure data in the Clouds
SecRBAC: Secure data in the Clouds
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Sql Server 2012
Sql Server 2012Sql Server 2012
Sql Server 2012
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
Ppt 1
Ppt 1Ppt 1
Ppt 1
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Cloud security ppt
Cloud security pptCloud security ppt
Cloud security ppt
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 
Cloud computing simple ppt
Cloud computing simple pptCloud computing simple ppt
Cloud computing simple ppt
 
Introduction of Cloud computing
Introduction of Cloud computingIntroduction of Cloud computing
Introduction of Cloud computing
 
cloud computing ppt
cloud computing pptcloud computing ppt
cloud computing ppt
 

Similar a 17 exceptions

MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11Terry Yoast
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 

Similar a 17 exceptions (20)

Java unit3
Java unit3Java unit3
Java unit3
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Chap12
Chap12Chap12
Chap12
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 

Más de dhrubo kayal

01 session tracking
01   session tracking01   session tracking
01 session trackingdhrubo kayal
 
03 handling requests
03 handling requests03 handling requests
03 handling requestsdhrubo kayal
 
02 up close with servlets
02 up close with servlets02 up close with servlets
02 up close with servletsdhrubo kayal
 
01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setupdhrubo kayal
 
14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanupdhrubo kayal
 
08 class and object
08   class and object08   class and object
08 class and objectdhrubo kayal
 
04 data types & variables
04   data types & variables04   data types & variables
04 data types & variablesdhrubo kayal
 
03 hello world with java
03   hello world with java03   hello world with java
03 hello world with javadhrubo kayal
 

Más de dhrubo kayal (20)

Cipla 20-09-2010
Cipla   20-09-2010Cipla   20-09-2010
Cipla 20-09-2010
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
 
03 handling requests
03 handling requests03 handling requests
03 handling requests
 
02 up close with servlets
02 up close with servlets02 up close with servlets
02 up close with servlets
 
01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup
 
19 reflection
19   reflection19   reflection
19 reflection
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
 
16 containers
16   containers16   containers
16 containers
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanup
 
13 inheritance
13   inheritance13   inheritance
13 inheritance
 
12 encapsulation
12   encapsulation12   encapsulation
12 encapsulation
 
11 static
11   static11   static
11 static
 
10 access control
10   access control10   access control
10 access control
 
09 packages
09   packages09   packages
09 packages
 
08 class and object
08   class and object08   class and object
08 class and object
 
07 flow control
07   flow control07   flow control
07 flow control
 
05 operators
05   operators05   operators
05 operators
 
04 data types & variables
04   data types & variables04   data types & variables
04 data types & variables
 
03 hello world with java
03   hello world with java03   hello world with java
03 hello world with java
 

17 exceptions

  • 2. Guarded section A block where you think some exceptional things – problem with data base connection, network failure, missing data – may happen try{ //code } try block
  • 3. The thrown exception must end up someplace – exception handler Exception 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 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
  • 5. 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
  • 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’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 cause Throwing Exceptions
  • 8. void f() throws TooBig, TooSmall, DivZero { //... void f() { //... This is not safe and can be vulnerable to RuntimeException and its likes Throwing Exceptions
  • 9. It is possible to create a handler that catches any type of exception by catching the base-class exception type Exception catch(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 Throwable String getMessage( ) String getLocalizedMessage( ) void printStackTrace( ) void printStackTrace(PrintStream) void printStackTrace(java.io.PrintWriter) Catching any Exception
  • 10. Write a Java code which first has an exception handler for Exception class followed by another exception handler for custom MyClass Excercise
  • 11. 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 exceptions Standard Java Exceptions
  • 12. RuntimeException and its children have special meaning to the runtime. They cause hazards without intimation – you do not declare them in the method exception specification They generally results of programming errors Use runtime exception if a you cannot recover from an operation If you are handling/catching RuntimeException there is problem in your code and design Unchecked 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 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
  • 15. 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
  • 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. Q&A