SlideShare a Scribd company logo
1 of 22
Free Ebooks DownloadFree Ebooks Download
Mba EbooksMba Ebooks
By Edhole
Mba ebooks
Free ebooks download
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Chapter 17 Exceptions andChapter 17 Exceptions and
AssertionsAssertions
Chapter 9 Inheritance and Polymorphism
Chapter 18 Binary I/O
Chapter 17 Exceptions and Assertions
Chapter 6 Arrays
Chapter 19 Recursion
2http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
ObjectivesObjectives
 To know what is exception and what is exception
handling (§17.2).
 To distinguish exception types: Error (fatal) vs.
Exception (non-fatal), and checked vs. uncheck
exceptions (§17.2).
 To declare exceptions in the method header (§17.3).
 To throw exceptions out of a method (§17.3).
 To write a try-catch block to handle exceptions (§17.3).
 To explain how an exception is propagated (§17.3).
 To rethrow exceptions in a try-catch block (§17.4).
 To use the finally clause in a try-catch block (§17.5).
 To know when to use exceptions (§17.6).
 To declare custom exception classes (§17.7 Optional).
 To apply assertions to help ensure program correctness
(§17.8).
3
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Syntax Errors, Runtime Errors, andSyntax Errors, Runtime Errors, and
Logic ErrorsLogic Errors
You learned that there are three
categories of errors: syntax errors,
runtime errors, and logic errors. Syntax
errors arise because the rules of the
language have not been followed. They
are detected by the compiler. Runtime
errors occur while the program is running
if the environment detects an operation
that is impossible to carry out. Logic
errors occur when a program doesn't
perform the way it was intended to.
4
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Runtime ErrorsRuntime Errors
5
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
}
}
If an exception occurs on this
line, the rest of the lines in the
method are skipped and the
program is terminated.
Terminated.
1
2
3
4
5
6
7
8
9
10
11
12
13
RunRun
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catch Runtime ErrorsCatch Runtime Errors
6
import java.util.*;
public class HandleExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
scanner.nextLine(); // discard input
}
} while (continueInput);
}
}
If an exception occurs on this line,
the rest of lines in the try block are
skipped and the control is
transferred to the catch block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
13
RunRun
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exception ClassesException Classes
7
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
System ErrorsSystem Errors
8
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
ExceptionsExceptions
9
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Runtime ExceptionsRuntime Exceptions
10
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked Exceptions vs.Checked Exceptions vs.
Unchecked ExceptionsUnchecked Exceptions
11
RuntimeException, Error and their subclasses are
known as unchecked exceptions. All other
exceptions are known as checked exceptions,
meaning that the compiler forces the programmer
to check and deal with the exceptions.
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Unchecked ExceptionsUnchecked Exceptions
12
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to
it; an IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array.
These are the logic errors that should be corrected in the
program. Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-catch
blocks, Java does not mandate you to write code to catch
unchecked exceptions.
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked or Unchecked ExceptionsChecked or Unchecked Exceptions
13
Unchecked
exception.
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring, Throwing, andDeclaring, Throwing, and
Catching ExceptionsCatching Exceptions
14
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
catch exception throw exception
declare exception
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring ExceptionsDeclaring Exceptions
Every method must state the types of
checked exceptions it might throw. This is
known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
15
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Throwing ExceptionsThrowing Exceptions
When the program detects an error, the
program can create an instance of an
appropriate exception type and throw it. This
is known as throwing an exception. Here is
an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
16
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Throwing ExceptionsThrowing Exceptions
ExampleExample
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentExceptionthrows IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
17http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catching ExceptionsCatching Exceptionstry {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
18http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catching ExceptionsCatching Exceptions
19
main method {
...
try {
...
invoke method1;
statement1;
}
catch (Exception1 ex1) {
Process ex1;
}
statement2;
}
method1 {
...
try {
...
invoke method2;
statement3;
}
catch (Exception2 ex2) {
Process ex2;
}
statement4;
}
method2 {
...
try {
...
invoke method3;
statement5;
}
catch (Exception3 ex3) {
Process ex3;
}
statement6;
}
An exception
is thrown in
method3
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catch or Declare CheckedCatch or Declare Checked
ExceptionsExceptions
Java forces you to deal with checked exceptions. If a method
declares a checked exception (i.e., an exception other than Error
or RuntimeException), you must invoke it in a try-catch block or
declare to throw the exception in the calling method. For
example, suppose that method p1 invokes method p2 and p2
may throw a checked exception (e.g., IOException), you have to
write the code as shown in (a) or (b).
20
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a) (b)
void p1() throws IOException {
p2();
}
http://ebooks.edhole.com
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: Declaring,Example: Declaring,
Throwing, and CatchingThrowing, and Catching
ExceptionsExceptions
Objective: This example demonstrates
declaring, throwing, and catching
exceptions by modifying the setRadius
method in the Circle class defined in
Chapter 6. The new setRadius method
throws an exception if radius is
negative.
21
TestCircleWithExceptionTestCircleWithException
RunRun
CircleWithExceptionCircleWithException
http://ebooks.edhole.com
Free Ebooks DownloadFree Ebooks Download
Mba EbooksMba Ebooks
By Edhole
Mba ebooks
Free ebooks download
http://ebooks.edhole.com

More Related Content

More from Edhole.com

More from Edhole.com (20)

Ca in patna
Ca in patnaCa in patna
Ca in patna
 
Chartered accountant in dwarka
Chartered accountant in dwarkaChartered accountant in dwarka
Chartered accountant in dwarka
 
Ca firm in dwarka
Ca firm in dwarkaCa firm in dwarka
Ca firm in dwarka
 
Ca in dwarka
Ca in dwarkaCa in dwarka
Ca in dwarka
 
Website development company surat
Website development company suratWebsite development company surat
Website development company surat
 
Website designing company in surat
Website designing company in suratWebsite designing company in surat
Website designing company in surat
 
Website designing company in india
Website designing company in indiaWebsite designing company in india
Website designing company in india
 
Website designing company in delhi
Website designing company in delhiWebsite designing company in delhi
Website designing company in delhi
 
Website designing company in mumbai
Website designing company in mumbaiWebsite designing company in mumbai
Website designing company in mumbai
 
Website development company surat
Website development company suratWebsite development company surat
Website development company surat
 
Website desinging company in surat
Website desinging company in suratWebsite desinging company in surat
Website desinging company in surat
 
Website designing company in india
Website designing company in indiaWebsite designing company in india
Website designing company in india
 
Website designing company in delhi
Website designing company in delhiWebsite designing company in delhi
Website designing company in delhi
 
Video lectures for mba
Video lectures for mbaVideo lectures for mba
Video lectures for mba
 
Video lecture for b.tech
Video lecture for b.techVideo lecture for b.tech
Video lecture for b.tech
 
Video lecture for bca
Video lecture for bcaVideo lecture for bca
Video lecture for bca
 
Mba top schools in india
Mba top schools in indiaMba top schools in india
Mba top schools in india
 
B.tech top schools in india
B.tech top schools in indiaB.tech top schools in india
B.tech top schools in india
 
Top schools in india
Top schools in indiaTop schools in india
Top schools in india
 
Mba admissions in india
Mba admissions in indiaMba admissions in india
Mba admissions in india
 

Recently uploaded

MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
Krashi Coaching
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Benefits and Challenges of OER by Shweta Babel.pptx
Benefits and Challenges of OER by Shweta Babel.pptxBenefits and Challenges of OER by Shweta Babel.pptx
Benefits and Challenges of OER by Shweta Babel.pptx
 
Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 

Free Ebooks Download ! Edhole

  • 1. Free Ebooks DownloadFree Ebooks Download Mba EbooksMba Ebooks By Edhole Mba ebooks Free ebooks download http://ebooks.edhole.com
  • 2. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Chapter 17 Exceptions andChapter 17 Exceptions and AssertionsAssertions Chapter 9 Inheritance and Polymorphism Chapter 18 Binary I/O Chapter 17 Exceptions and Assertions Chapter 6 Arrays Chapter 19 Recursion 2http://ebooks.edhole.com
  • 3. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 ObjectivesObjectives  To know what is exception and what is exception handling (§17.2).  To distinguish exception types: Error (fatal) vs. Exception (non-fatal), and checked vs. uncheck exceptions (§17.2).  To declare exceptions in the method header (§17.3).  To throw exceptions out of a method (§17.3).  To write a try-catch block to handle exceptions (§17.3).  To explain how an exception is propagated (§17.3).  To rethrow exceptions in a try-catch block (§17.4).  To use the finally clause in a try-catch block (§17.5).  To know when to use exceptions (§17.6).  To declare custom exception classes (§17.7 Optional).  To apply assertions to help ensure program correctness (§17.8). 3 http://ebooks.edhole.com
  • 4. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Syntax Errors, Runtime Errors, andSyntax Errors, Runtime Errors, and Logic ErrorsLogic Errors You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. Logic errors occur when a program doesn't perform the way it was intended to. 4 http://ebooks.edhole.com
  • 5. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Runtime ErrorsRuntime Errors 5 import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); } } If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated. Terminated. 1 2 3 4 5 6 7 8 9 10 11 12 13 RunRun http://ebooks.edhole.com
  • 6. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Catch Runtime ErrorsCatch Runtime Errors 6 import java.util.*; public class HandleExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean continueInput = true; do { try { System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextLine(); // discard input } } while (continueInput); } } If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch block. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 13 RunRun http://ebooks.edhole.com
  • 7. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Exception ClassesException Classes 7 http://ebooks.edhole.com
  • 8. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 System ErrorsSystem Errors 8 System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. http://ebooks.edhole.com
  • 9. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 ExceptionsExceptions 9 Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. http://ebooks.edhole.com
  • 10. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Runtime ExceptionsRuntime Exceptions 10 RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. http://ebooks.edhole.com
  • 11. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Checked Exceptions vs.Checked Exceptions vs. Unchecked ExceptionsUnchecked Exceptions 11 RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. http://ebooks.edhole.com
  • 12. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Unchecked ExceptionsUnchecked Exceptions 12 In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions. http://ebooks.edhole.com
  • 13. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Checked or Unchecked ExceptionsChecked or Unchecked Exceptions 13 Unchecked exception. http://ebooks.edhole.com
  • 14. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Declaring, Throwing, andDeclaring, Throwing, and Catching ExceptionsCatching Exceptions 14 method1() { try { invoke method2; } catch (Exception ex) { Process exception; } } method2() throws Exception { if (an error occurs) { throw new Exception(); } } catch exception throw exception declare exception http://ebooks.edhole.com
  • 15. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Declaring ExceptionsDeclaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException 15 http://ebooks.edhole.com
  • 16. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Throwing ExceptionsThrowing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex; 16 http://ebooks.edhole.com
  • 17. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Throwing ExceptionsThrowing Exceptions ExampleExample /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentExceptionthrows IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } 17http://ebooks.edhole.com
  • 18. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Catching ExceptionsCatching Exceptionstry { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; } 18http://ebooks.edhole.com
  • 19. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Catching ExceptionsCatching Exceptions 19 main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } statement2; } method1 { ... try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; } statement4; } method2 { ... try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; } statement6; } An exception is thrown in method3 http://ebooks.edhole.com
  • 20. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Catch or Declare CheckedCatch or Declare Checked ExceptionsExceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). 20 void p1() { try { p2(); } catch (IOException ex) { ... } } (a) (b) void p1() throws IOException { p2(); } http://ebooks.edhole.com
  • 21. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Example: Declaring,Example: Declaring, Throwing, and CatchingThrowing, and Catching ExceptionsExceptions Objective: This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method in the Circle class defined in Chapter 6. The new setRadius method throws an exception if radius is negative. 21 TestCircleWithExceptionTestCircleWithException RunRun CircleWithExceptionCircleWithException http://ebooks.edhole.com
  • 22. Free Ebooks DownloadFree Ebooks Download Mba EbooksMba Ebooks By Edhole Mba ebooks Free ebooks download http://ebooks.edhole.com