SlideShare a Scribd company logo
Exceptions Handling
Compiled by Hashim S.
Chapter 4
Exceptions
 An exception is an object that describes an unusual or
erroneous situation
 Exceptions are thrown by a program, and may be caught and
handled by another part of the program
Exception Hierarchy
 Errors:
 Errors are fairly rare and usually fatal. They are caused by
bugs in the Java VM, or by the program running out of
memory or other resources.
 Errors are usually not handled by programs.
 Exceptions:
 Exceptions can be caused by bugs in the program or improper
data supplied to the program
 Exceptions should be handled, or caught
 An exception is either checked or unchecked
 Checked exceptions must be fixed or declared as thrown.
 You are not required to handle unchecked exceptions.
Attack of the Exception
 What happens when this method is used to take the average of
an array of length zero?
 Program throws an Exception and fails
java.lang.ArithmeticException: / by zero
public static int average(int[] a) {
int total = 0;
int total1=0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total /total1;
}
What is an Exception?
 An error event that disrupts the program flow and may
cause a program to fail.
 Some examples:
 Performing illegal arithmetic
 Illegal arguments to methods
 Accessing an out-of-bounds array element
 Hardware failures
 Writing to a read-only file
Another Exception Example
 What is the output of this program?
public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}
Output:
Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Message Details
 What exception class?
 Which array index is out of bounds?
 What method throws the exception?
 What file contains the method?
 What line of the file throws the exception?
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
ArrayIndexOutOfBoundsException
2
main
ExceptionExample.java
4
8
Classifying Java Exceptions
 Unchecked Exceptions
 All the exceptions we've seen so far have been Unchecked
Exceptions, or Runtime Exceptions
 Usually occur because of programming errors, when code is
not robust enough to prevent them
 They are numerous and can be ignored by the programmer
 Common Unchecked Exceptions

NullPointerException: reference is null and should not be

IllegalArgumentException: method argument is improper is
some way

IllegalStateException: method called when class is in improper
state
 Checked Exceptions
 Usually occur because of errors programmer cannot control

examples: hardware failures, unreadable files
 They are less frequent and they cannot be ignored by the
programmer . . .
 Every method must catch (handle) checked exceptions or
specify that it may throw them
 Specify with the throws keyword
Checked and Unchecked Exceptions
Checked Exception Unchecked Exception
not subclass of RuntimeException subclass of RuntimeException
if not caught, method must specify it
to be thrown
if not caught, method may specify it
to be thrown
for errors that the programmer
cannot directly prevent from
occurring
for errors that the programmer can
directly prevent from occurring,
IOException,
FileNotFoundException,
SocketException
NullPointerException,
IllegalArgumentException,
IllegalStateException
Exception Class Hierarchy
Exception
RuntimeException IOException
FileNotFoundException
MalformedURLException
SocketException
ArrayIndexOutofBounds
NullPointerException
etc. etc.
SQLException
IllegalArgumentException
Unchecked Exceptions Checked Exceptions
 All exceptions are instances of classes that are subclasses
of Exception
12
Keywords for Java Exceptions
 throws: - Describes the exceptions which can be raised by a
method.
 throw: - Raises an exception to the first available handler in
the call stack, unwinding the stack along the way.
 try: - Marks the start of a block associated with a set of
exception handlers.
 catch: - If the block enclosed by the try generates an
exception of this type, control moves here; watch out for
implicit subsumption .
 finally: - Always called when the try block concludes, and
after any necessary catch handler is complete.
Exceptions Terminology
 When an exception happens we say it was thrown or
raised
 When an exception is dealt with, we say the exception is
handled or caught
Exception Handling
 Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Exception Handling Example
public static int average(int[] a) {
int total = 0;
int tot1=0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / tot1;
}
public static void printAverage(int[] a) {
try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
}
Catching Multiple Exceptions
 Handle multiple possible exceptions by multiple successive
catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
Exception Constructors
 Exceptions have at least two constructors:
1. no arguments
NullPointerException e = new
NullPointerException();
2. single String argument descriptive message that appears when
exception error message is printed
IllegalArgumentExceptione e =
new IllegalArgumentException("number must be positive");
Writing Your Own Exception
 To write your own exception, write a subclass of Exception
and write both types of constructors
public class MyCheckedException extends IOException {
public MyCheckedException() {}
public MyCheckedException(String m) {
super(m);
}
}
public class MyUncheckedException extends RuntimeException {
public MyUncheckedException() {}
public MyUncheckedException(String m) {
super(m);
}
}
Throwing Exceptions
 Throw exception with the throw keyword
public static int average(int[] a) {
if (a.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
Throw Statement and Throws Clause
public class MyClass {
public void aMethod(int i, int j) throws MyException {
// ...
throw new MyException(reason);
// ...
}
}
Throws and Inheritance
 A method can throw less exceptions, but not more, than the
method it is overriding
public class MyClass {
public void doSomething() throws IOException, SQLException {
// do something here
}
}
public class MySubclass extends MyClass {
public void doSomething() throws IOException {
// do here
}
}

More Related Content

PPTX
Z blue exception
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPT
Exception handling
PPTX
Interface andexceptions
PPTX
Exception handling
PPTX
Java -Exception handlingunit-iv
PPTX
UNIT 2.pptx
PPTX
Java exception handling
Z blue exception
unit 4 msbte syallbus for sem 4 2024-2025
Exception handling
Interface andexceptions
Exception handling
Java -Exception handlingunit-iv
UNIT 2.pptx
Java exception handling

Similar to Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt (20)

PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PDF
Class notes(week 8) on exception handling
PPTX
java exception.pptx
PPTX
UNIT-3.pptx Exception Handling and Multithreading
PPT
Exceptionhandling
DOCX
Exception handling in java
PPTX
Exception handling in Java
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
PPTX
presentation-on-exception-handling 1.pptx
PDF
Java unit 11
PDF
Java exceptions
PPT
Exception Handling in JAVA
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
Exceptions handling in java
PPTX
Exception‐Handling in object oriented programming
PPS
Java Exception handling
PPT
Exception handling
PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
Class notes(week 8) on exception handling
java exception.pptx
UNIT-3.pptx Exception Handling and Multithreading
Exceptionhandling
Exception handling in java
Exception handling in Java
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling 1.pptx
Java unit 11
Java exceptions
Exception Handling in JAVA
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
Exceptions handling in java
Exception‐Handling in object oriented programming
Java Exception handling
Exception handling
Exception Handling,finally,catch,throw,throws,try.pptx
Ad

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PDF
Business Ethics Teaching Materials for college
PDF
From loneliness to social connection charting
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Week 4 Term 3 Study Techniques revisited.pptx
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
NOI Hackathon - Summer Edition - GreenThumber.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Open Quiz Monsoon Mind Game Prelims.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pre independence Education in Inndia.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Cardiovascular Pharmacology for pharmacy students.pptx
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
UPPER GASTRO INTESTINAL DISORDER.docx
O7-L3 Supply Chain Operations - ICLT Program
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Business Ethics Teaching Materials for college
From loneliness to social connection charting
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Ad

Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt

  • 1. Exceptions Handling Compiled by Hashim S. Chapter 4
  • 2. Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown by a program, and may be caught and handled by another part of the program
  • 3. Exception Hierarchy  Errors:  Errors are fairly rare and usually fatal. They are caused by bugs in the Java VM, or by the program running out of memory or other resources.  Errors are usually not handled by programs.  Exceptions:  Exceptions can be caused by bugs in the program or improper data supplied to the program  Exceptions should be handled, or caught  An exception is either checked or unchecked  Checked exceptions must be fixed or declared as thrown.  You are not required to handle unchecked exceptions.
  • 4. Attack of the Exception  What happens when this method is used to take the average of an array of length zero?  Program throws an Exception and fails java.lang.ArithmeticException: / by zero public static int average(int[] a) { int total = 0; int total1=0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total /total1; }
  • 5. What is an Exception?  An error event that disrupts the program flow and may cause a program to fail.  Some examples:  Performing illegal arithmetic  Illegal arguments to methods  Accessing an out-of-bounds array element  Hardware failures  Writing to a read-only file
  • 6. Another Exception Example  What is the output of this program? public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha", "Beta"}; System.out.println(greek[2]); } } Output: Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)
  • 7. Exception Message Details  What exception class?  Which array index is out of bounds?  What method throws the exception?  What file contains the method?  What line of the file throws the exception? Exception message format: [exception class]: [additional description of exception] at [class].[method]([file]:[line number]) Example: java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4) ArrayIndexOutOfBoundsException 2 main ExceptionExample.java 4
  • 8. 8 Classifying Java Exceptions  Unchecked Exceptions  All the exceptions we've seen so far have been Unchecked Exceptions, or Runtime Exceptions  Usually occur because of programming errors, when code is not robust enough to prevent them  They are numerous and can be ignored by the programmer  Common Unchecked Exceptions  NullPointerException: reference is null and should not be  IllegalArgumentException: method argument is improper is some way  IllegalStateException: method called when class is in improper state
  • 9.  Checked Exceptions  Usually occur because of errors programmer cannot control  examples: hardware failures, unreadable files  They are less frequent and they cannot be ignored by the programmer . . .  Every method must catch (handle) checked exceptions or specify that it may throw them  Specify with the throws keyword
  • 10. Checked and Unchecked Exceptions Checked Exception Unchecked Exception not subclass of RuntimeException subclass of RuntimeException if not caught, method must specify it to be thrown if not caught, method may specify it to be thrown for errors that the programmer cannot directly prevent from occurring for errors that the programmer can directly prevent from occurring, IOException, FileNotFoundException, SocketException NullPointerException, IllegalArgumentException, IllegalStateException
  • 11. Exception Class Hierarchy Exception RuntimeException IOException FileNotFoundException MalformedURLException SocketException ArrayIndexOutofBounds NullPointerException etc. etc. SQLException IllegalArgumentException Unchecked Exceptions Checked Exceptions  All exceptions are instances of classes that are subclasses of Exception
  • 12. 12 Keywords for Java Exceptions  throws: - Describes the exceptions which can be raised by a method.  throw: - Raises an exception to the first available handler in the call stack, unwinding the stack along the way.  try: - Marks the start of a block associated with a set of exception handlers.  catch: - If the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption .  finally: - Always called when the try block concludes, and after any necessary catch handler is complete.
  • 13. Exceptions Terminology  When an exception happens we say it was thrown or raised  When an exception is dealt with, we say the exception is handled or caught
  • 14. Exception Handling  Use a try-catch block to handle exceptions that are thrown try { // code that might throw exception } catch ([Type of Exception] e) { // what to do if exception is thrown }
  • 15. Exception Handling Example public static int average(int[] a) { int total = 0; int tot1=0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / tot1; } public static void printAverage(int[] a) { try { int avg = average(a); System.out.println("the average is: " + avg); } catch (ArithmeticException e) { System.out.println("error calculating average"); } }
  • 16. Catching Multiple Exceptions  Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception } catch (IOException e) { // handle IOException and all subclasses } catch (ClassNotFoundException e2) { // handle ClassNotFoundException }
  • 17. Exception Constructors  Exceptions have at least two constructors: 1. no arguments NullPointerException e = new NullPointerException(); 2. single String argument descriptive message that appears when exception error message is printed IllegalArgumentExceptione e = new IllegalArgumentException("number must be positive");
  • 18. Writing Your Own Exception  To write your own exception, write a subclass of Exception and write both types of constructors public class MyCheckedException extends IOException { public MyCheckedException() {} public MyCheckedException(String m) { super(m); } } public class MyUncheckedException extends RuntimeException { public MyUncheckedException() {} public MyUncheckedException(String m) { super(m); } }
  • 19. Throwing Exceptions  Throw exception with the throw keyword public static int average(int[] a) { if (a.length == 0) { throw new IllegalArgumentException("array is empty"); } int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; }
  • 20. Throw Statement and Throws Clause public class MyClass { public void aMethod(int i, int j) throws MyException { // ... throw new MyException(reason); // ... } }
  • 21. Throws and Inheritance  A method can throw less exceptions, but not more, than the method it is overriding public class MyClass { public void doSomething() throws IOException, SQLException { // do something here } } public class MySubclass extends MyClass { public void doSomething() throws IOException { // do here } }

Editor's Notes

  • #8: Runtime exceptions make it impossible to know what exceptions can be emitted by a method. They also result in incosistent throws decls among developers. Describe subsumption to people: subsumption is often how IOException derivatives are dealt with (subsumption is casting to the base class). The most vituperative debate is between those who believe unchecked exceptions make mechanical testing nearly impossible, and those who believe that checked exceptions impinge on polymorphism by making the exception list part of the method signature (and thereby inheritable).
  • #18: Note that not necessarily a direct subclass
  • #19: Ask Class: Is IllegalArgumentException checked or unchecked?