Handling Exceptions in Java Programming

Exceptions
"A slipping gear could let your M203 grenade launcher
fire when you least expect it. That would make you
quite unpopular in what's left of your unit."
 
-
 THE U.S. Army's PS magazine, August 1993, 
quoted in
 The Java
Programming Language, 3rd edition
 
When Good Programs Go Bad
8
A variety of problems can occur when a
program is running.
User input error: 
bad url
Device errors: 
remote server unavailable
Physical limitations: 
disk full
Code errors: 
code that does not fulfill its contact
(i.e. pre- and post-conditions)
8
When a problem occurs,
return to safe state, save work, exit gracefully.
8
Code that handles a problem may be far
removed from code that caused it.
Computer Science II
2
How to Handle Problems?
8
It’s possible to detect and handle problems
of various types.
8
Issue: complicates code and makes it harder
to understand.
Problem detection and problem handling code
have little or nothing to do with what the 
real
code is trying to do.
8
Tradeoff between ensuring correct behavior
under all possible circumstances and clarity
of the code.
Computer Science II
3
Handling Problems in Java
8
Based on that of C++, but more in line with
OOP philosophy.
8
All errors/exceptions are objects of classes
that extend the 
Throwable
 class.
Computer Science II
Computer Science II
4
Classes of Exceptions
8
The Java library includes two important
subclasses of 
Throwable
 class:
Error
Thrown by the Java interpreter for events such as
heap overflow
.
Never handled by user programs.
Exception
User-defined exceptions are usually sub-classes of
this.
Has two predefined subclasses:
IOException
RuntimeException
Computer Science II
Computer Science II
5
Error / Exception Classes
Computer Science II
6
Throwable
 Class Methods
Computer Science II
7
Exceptions
 
8
Many languages, including Java, use the
exception-handling process to handle
runtime problems.
In Java, 
Exception
 is a class with many
descendants.
For example:
ArrayIndexOutOfBoundsException
NullPointerException
FileNotFoundException
ArithmeticException
IllegalArgumentException
Computer Science II
8
Handling Exceptions
8
Exceptions in Java fall into two different
categories:
Checked
 exception (compile-time)
Must be caught in 
catch
 block.
Or declared in 
throws
 clause.
Unchecked
 exception (run-time)
Need not be caught in 
catch
 block or declared in
throws
.
Exceptions errors in code that should be fixed.
Computer Science II
9
Unchecked Exceptions
8
U
n
c
h
e
c
k
e
d
 
e
x
c
e
p
t
i
o
n
s
 
a
r
e
 
c
o
m
p
l
e
t
e
l
y
p
r
e
v
e
n
t
a
b
l
e
 
a
n
d
 
s
h
o
u
l
d
 
n
e
v
e
r
 
o
c
c
u
r
.
Caused by logic errors, created by programmers.
Descendents of the 
RuntimeException
 class.
8
There does not 
need
 to be special error
handling code.
Just regular error prevention code.
8
If error handling code was required,
programs would be unwieldy.
Computer Science II
10
10
Unchecked Runtime Exceptions
Computer Science II
11
11
Checked Exceptions
8
"Checked exceptions represent conditions
that, although exceptional, can reasonably
be expected to occur, and if they do occur
must be dealt with in some way [other than
the program terminating]."
Java Programming Language, Third Edition
8
Checked exceptions represent errors that
are have to be handled by programmers.
Computer Science II
12
12
Checked Exceptions
Computer Science II
13
13
When Exceptions Occur
8
When an exception occurs, the normal flow of
control of a program halts.
8
The method where the exception occurred creates
an exception object of the appropriate type.
The object contains information about the error.
Then hands exception to the Java Runtime
System(JRS).
8
The JRS searches for a matching 
catch
 block for
the exception.
8
The first matching 
catch
 block is executed.
8
When the 
catch
 block code is completed, the
program executes the next regular statement after
the 
catch
 block.
Computer Science II
14
14
Call Stack
8
After a method throws an exception, the JRS looks
for a method with a 
catch
 block to handle it. This
block of code is called the 
exception handler
.
8
If the method that threw the exception can’t handle
it, the JRS looks in the ordered list of methods that
have been called to get to this method. This list of
methods is known as the 
call stack
.
Computer Science II
15
15
Exception Handler
8
When an appropriate handler is found, the JRS
passes the exception to the handler.
8
An exception handler is considered appropriate if
the type of exception thrown matches the type of
exceptions that can be handled by the handler, or
inherits from one.
8
If the JRS searches the whole call stack without
finding an appropriate exception handler, the
program crashes.
Computer Science II
16
16
Catching Exceptions
8
A method surrounds code that may cause an
exceptions with a 
try
 block.
8
The 
catch
 statement declares type of exception
trying to catch. If an exception or that type or one of
its descendants occurs, the exception is passed on
to that block for processing.
Computer Science II
try
{
 
//Protected code
}
catch(ExceptionName e1)
{
 
//Catch block
}
17
17
An Example
Computer Science II
// File Name : ExcepTest.java
public class ExcepTest
{
   public static void main(String args[])
   { 
 
 
try
 
{
          int a[] = new int[2];
          System.out.println("Access element three :" + a[3]);
 
}
 
catch(ArrayIndexOutOfBoundsException e)
 
{
 
   System.out.println("Exception thrown :" + e);
 
}
 
System.out.println("Out of the block");
   }
}
18
18
Example Output
8
The above code would produce the following
result:
Computer Science II
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
19
19
Multiple 
Catch
 Blocks
8
A 
try
 block can be followed by multiple 
catch
blocks.
Computer Science II
try
{
 
//Protected code
}
catch(ExceptionType1 e1)
{
 
//Catch block
}
catch(ExceptionType2 e2)
{
 
//Catch block
}
catch(ExceptionType3 e3)
{
 
//Catch block
}
20
20
Example-Multiple Catch Blocks
Computer Science II
try
{
 
file = new FileInputStream(fileName);
 
x = file.read();
}
catch(FileNotFoundException f)
{
 
f.printStackTrace();
}
catch(IOException i)
{
 
i.printStackTrace();
}
21
21
throws
 Keyword
8
I
f
 
a
 
m
e
t
h
o
d
 
d
o
e
s
 
n
o
t
 
h
a
n
d
l
e
 
a
 
c
h
e
c
k
e
d
e
x
c
e
p
t
i
o
n
,
 
t
h
e
 
m
e
t
h
o
d
 
m
u
s
t
 
d
e
c
l
a
r
e
 
i
t
u
s
i
n
g
 
t
h
e
 
t
h
r
o
w
s
 
k
e
y
w
o
r
d
.
Computer Science II
import java.io.*;
public class ClassName
{
 
public int read(FileStream file) throws IOException
 
{
 
    int x = file.read(); 
 
 
}
}
22
22
Multiple Exceptions Thrown
8
A method can throw more than one
exception.
Exceptions are declared in a list separated
by commas.
Computer Science II
import java.io.*;
public class ClassName
{
  public int read(String fileName) throws
FileNotFoundException, IOException
  {
 
FileStream file = new FileInputStream(filename);
 
int x file.read();
  }
}
23
23
finally
 Block
8
The 
finally
 keyword used to create a block
of code that follows a try block.
Always executes, whether or not an exception has
occurred.
Runs any cleanup-type statements that you want
to execute.
Appears after the 
catch
 blocks.
Computer Science II
try
{ //Protected code
}
catch(ExceptionType e)
{ //Catch block
}
finally
{ //The finally block always executes.
}
24
24
Example – 
finally
 Block
Computer Science II
public class ExcepTest
{
  public static void main(String args[])
  {
 
int a[] = new int[2];
 
try
 
{
 
  System.out.println("Access element three :" + a[3]);
 
}
 
catch(ArrayIndexOutOfBoundsException e)
 
{
 
  System.out.println("Exception thrown :" + e);
 
}
 
finally
 
{
 
  a[0] = 6; System.out.println("First element value: " +a[0]);
 
  System.out.println("The finally statement is executed");
 
}
  }
}
25
25
Example Output
8
Would produce this result:
Computer Science II
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
26
26
Things to Note
8
Must follow a 
try
 block with either
catch
 and/or 
finally
 block.
8
Catch
 blocks must follow a 
try
statement.
8
A 
finally
 block is not required if
there are 
try-catch
 blocks.
8
try
, 
catch
, 
finally
 blocks must
follow each other in that order.
There cannot be any code between them.
Computer Science II
27
27
Throwing Exceptions Yourself
8
If you wish to throw an exception in your code, you
use the 
throw
 keyword.
8
Most common would be for an unmet precondition.
public class Circle
{
 
private double radius;
 
// other variables and methods
 
public setRadius(int radius){
 
  
if (radius <= 0)
   
throw new IllegalArgumentException
    
("radius must be > 0. "
    
+ "Value of radius: " + radius);
  
this.radius = radius;
  
// other unrelated code
 
}
}
Computer Science II
28
28
Errors
8
An 
error
 is an object of class 
Error
.
Similar to an unchecked exception.
Need not catch or declare in throws clause.
Object of class 
Error
 generated when
abnormal conditions occur.
8
Error
s are more or less beyond your
control.
Require change of program to resolve.
Computer Science II
29
29
Question 1
 
What is output by the method 
badUse
 if it is called with the
following code?
  
 
int[] nums = {3, 2, 6, 1};
badUse( nums );
  
   public static void badUse(int[] vals){
    int total = 0;
    try{
        for(int i = 0; i < vals.length; i++){
            int index = vals[i];
            total += vals[index];
        }
      }
    catch(Exception e){
        total = -1;
    }
    System.out.println(total);
}
A. 
12
  
B. 
0
  
C. 
3
  
D. 
-1
  
E. 
5
Computer Science II
30
30
Question 1
 
What is output by the method 
badUse
 if it is called with the
following code?
  
 
int[] nums = {3, 2, 6, 1};
badUse( nums );
  
   public static void badUse(int[] vals){
    int total = 0;
    try{
        for(int i = 0; i < vals.length; i++){
            int index = vals[i];
            total += vals[index];
        }
      }
    catch(Exception e){
        total = -1;
    }
    System.out.println(total);
}
A. 
12
  
B. 
0
  
C. 
3
  
D. 
-1
  
E. 
5
Computer Science II
31
31
Question 2
 
Is the use of a 
try-catch
 block on the
previous question a proper use of 
try-
catch
 blocks?
  
A. Yes
  
B. No
Computer Science II
32
32
Question 2
 
Is the use of a 
try-catch
 block on the
previous question a proper use of 
try-catch
blocks?
  
A. Yes
  
B. No
What is a better way to handle this type of error?
Computer Science II
33
33
Advantages of Exceptions
8
Separates Exception-Handling Code from
"Regular" Code
Means to separate the details of what to do when something
out of the ordinary happens from the main logic of a
program.
8
Propagating Exceptions Down the Call Stack
Ability to propagate error reporting down the call stack of
methods.
8
Grouping and Differentiating Error Types
Since all exceptions thrown within a program are objects, the
grouping or categorizing of exceptions is a natural outcome
of the class hierarchy.
Computer Science II
34
34
 
 
Computer Science II
35
35
Creating Exceptions
8
All exceptions must inherit from the 
Throwable
class.
8
If you want to write a 
checked
 exception, extend the
Exception
 class.
8
If you want to write an unchecked exception, extend
the 
RuntimeException
 class.
8
Define at least two constructors:
1.
Default, no parameters.
2.
Another with 
String
 parameter representing a message.
For both, call constructor of base class.
8
Do not override inherited 
getMessage
.
Computer Science II
36
36
Example–Creating Exceptions
Computer Science II
// File Name MyException.java
import java.io.*;
public class MyException extends Exception
{
 
public MyException(String msg)
 
{
  
super(msg);
 
}
}
37
37
Computer Science II
Assertions
8
Statements in the program declaring a Boolean
expression about the current state of variables
8
If evaluate to 
true
, nothing happens
8
If evaluate to 
false,
 an 
AssertionError
exception is thrown
8
Can be disabled during runtime without program
modification or recompilation
8
Two forms
assert 
condition
;
assert 
condition
: 
expression
;
38
38
Error Handling, Error Handling
Everywhere!
8
Seems like a lot of choices for error
prevention and error handling
normal program logic (e.g. 
if
s, 
for
-loop
counters)
assertions
try-catch 
block
8
When is it appropriate to use each kind?
Computer Science II
39
39
Error Prevention
8
Use program logic (
if
s , 
for
s) to
prevent 
logic errors
 and unchecked
exceptions
dereferencing a null pointer
going outside the bounds of an array
violating the preconditions of a method you
are calling
Computer Science II
40
40
Error Prevention – cont’d
8
In general, don’t use asserts to check
preconditions
Standard Java style is to use exceptions
8
Use 
try-catch
 blocks on checked
exceptions
Don’t use them to handle unchecked exceptions,
like null pointer or array index out of bounds
8
One place it is reasonable to use 
try-
catch 
is in testing suites.
put each test in a 
try-catch
. If an exception
occurs that test fails, but other tests can still be
run
Computer Science II
41
41
Slide Note
Embed
Share

Problems can arise during program execution, ranging from user input errors to device failures and code errors. It is essential to handle these exceptions effectively to ensure the stability and reliability of the program. In Java, exceptions are represented as objects and categorized into different classes, providing a structured approach to error handling. Understanding exception classes and methods can help developers manage issues and maintain the integrity of their code.

  • Java programming
  • Exception handling
  • Error classes
  • Program stability
  • Code reliability

Uploaded on Oct 04, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Exceptions "A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your unit." - THE U.S. Army's PS magazine, August 1993, quoted in The Java Programming Language, 3rd edition

  2. When Good Programs Go Bad A variety of problems can occur when a program is running. User input error: bad url Device errors: remote server unavailable Physical limitations: disk full Code errors: code that does not fulfill its contact (i.e. pre- and post-conditions) When a problem occurs, return to safe state, save work, exit gracefully. Code that handles a problem may be far removed from code that caused it. Computer Science II 2

  3. How to Handle Problems? It s possible to detect and handle problems of various types. Issue: complicates code and makes it harder to understand. Problem detection and problem handling code have little or nothing to do with what the real code is trying to do. Tradeoff between ensuring correct behavior under all possible circumstances and clarity of the code. Computer Science II 3

  4. Handling Problems in Java Based on that of C++, but more in line with OOP philosophy. All errors/exceptions are objects of classes that extend the Throwable class. Computer Science II Computer Science II 4

  5. Classes of Exceptions The Java library includes two important subclasses of Throwable class: Error Thrown by the Java interpreter for events such as heap overflow. Never handled by user programs. Exception User-defined exceptions are usually sub-classes of this. Has two predefined subclasses: IOException RuntimeException Computer Science II Computer Science II 5

  6. Error / Exception Classes ClassNotFoundException IOException ArithmeticException Exception AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException Several more classes LinkageError VirtualMachineError Error AWTError Several more classes Computer Science II 6

  7. Throwable Class Methods Methods with Description public String getMessage Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getCause Returns the cause of the exception as represented by a Throwable object. public String toString Returns the name of the class concatenated with the result of getMessage() public void printStackTrace Prints the result of toString() along with the stack trace to System.err, the error output stream. public StackTraceElement[] getStackTrace Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillInStackTrace Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. Computer Science II 7

  8. Exceptions Many languages, including Java, use the exception-handling process to handle runtime problems. In Java, Exception is a class with many descendants. For example: ArrayIndexOutOfBoundsException NullPointerException FileNotFoundException ArithmeticException IllegalArgumentException Computer Science II 8

  9. Handling Exceptions Exceptions in Java fall into two different categories: Checked exception (compile-time) Must be caught in catch block. Or declared in throws clause. Unchecked exception (run-time) Need not be caught in catch block or declared in throws. Exceptions errors in code that should be fixed. Computer Science II 9

  10. Unchecked Exceptions Unchecked exceptions are completely preventable and should never occur. Caused by logic errors, created by programmers. Descendents of the RuntimeException class. There does not need to be special error handling code. Just regular error prevention code. If error handling code was required, programs would be unwieldy. Computer Science II 10

  11. Unchecked Runtime Exceptions Exception Description Arithmetic error, such as divide-by-zero. ArithmeticException ArrayIndexOutOfBoundsExcepti on Array index is out-of-bounds. Assignment to an array element of an incompatible type. ArrayStoreException Invalid cast. ClassCastException Illegal argument used to invoke a method. IllegalArgumentException Illegal monitor operation, such as waiting on an unlocked thread. IllegalMonitorStateException Environment or application is in incorrect state. IllegalStateException Requested operation not compatible with current thread state. IllegalThreadStateException Some type of index is out-of-bounds. IndexOutOfBoundsException Array created with a negative size. Invalid use of a null reference. NegativeArraySizeException NullPointerException Invalid conversion of a string to a numeric format. NumberFormatException Attempt to violate security. SecurityException Attempt to index outside the bounds of a string. StringIndexOutOfBounds UnsupportedOperationExceptio n An unsupported operation was encountered. Computer Science II 11

  12. Checked Exceptions "Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some way [other than the program terminating]." Java Programming Language, Third Edition Checked exceptions represent errors that are have to be handled by programmers. Computer Science II 12

  13. Checked Exceptions Exception ClassNotFoundException Description Class not found. Attempt to clone an object that does not implement the Cloneable interface. Access to a class is denied. Attempt to create an object of an abstract class or interface. One thread has been interrupted by another thread. A requested field does not exist. A requested method does not exist. CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException Computer Science II 13

  14. When Exceptions Occur When an exception occurs, the normal flow of control of a program halts. The method where the exception occurred creates an exception object of the appropriate type. The object contains information about the error. Then hands exception to the Java Runtime System(JRS). The JRS searches for a matching catch block for the exception. The first matching catch block is executed. When the catch block code is completed, the program executes the next regular statement after the catch block. Computer Science II 14

  15. Call Stack After a method throws an exception, the JRS looks for a method with a catch block to handle it. This block of code is called the exception handler. If the method that threw the exception can t handle it, the JRS looks in the ordered list of methods that have been called to get to this method. This list of methods is known as the call stack. Computer Science II 15

  16. Exception Handler When an appropriate handler is found, the JRS passes the exception to the handler. An exception handler is considered appropriate if the type of exception thrown matches the type of exceptions that can be handled by the handler, or inherits from one. If the JRS searches the whole call stack without finding an appropriate exception handler, the program crashes. Computer Science II 16

  17. Catching Exceptions A method surrounds code that may cause an exceptions with a try block. try { //Protected code } catch(ExceptionName e1) { //Catch block } The catch statement declares type of exception trying to catch. If an exception or that type or one of its descendants occurs, the exception is passed on to that block for processing. Computer Science II 17

  18. An Example // File Name : ExcepTest.java public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } Computer Science II 18

  19. Example Output The above code would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Computer Science II 19

  20. Multiple Catch Blocks A try block can be followed by multiple catch blocks. try { } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } //Protected code Computer Science II 20

  21. Example-Multiple Catch Blocks try { } catch(FileNotFoundException f) { f.printStackTrace(); } catch(IOException i) { i.printStackTrace(); } file = new FileInputStream(fileName); x = file.read(); Computer Science II 21

  22. throws Keyword If a method does not handle a checked exception, the method must declare it using the throwskeyword. import java.io.*; public class ClassName { public int read(FileStream file) throws IOException { int x = file.read(); } } Computer Science II 22

  23. Multiple Exceptions Thrown A method can throw more than one exception. Exceptions are declared in a list separated by commas. import java.io.*; public class ClassName { public int read(String fileName) throws FileNotFoundException, IOException { FileStream file = new FileInputStream(filename); int x file.read(); } } Computer Science II 23

  24. finally Block The finally keyword used to create a block of code that follows a try block. Always executes, whether or not an exception has occurred. Runs any cleanup-type statements that you want to execute. Appears after the catch blocks. try { //Protected code } catch(ExceptionType e) { //Catch block } finally { //The finally block always executes. } Computer Science II 24

  25. Example finally Block public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } Computer Science II 25

  26. Example Output Would produce this result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Computer Science II 26

  27. Things to Note Must follow a try block with either catch and/or finally block. Catch blocks must follow a try statement. A finally block is not required if there are try-catch blocks. try, catch, finally blocks must follow each other in that order. There cannot be any code between them. Computer Science II 27

  28. Throwing Exceptions Yourself If you wish to throw an exception in your code, you use the throw keyword. Most common would be for an unmet precondition. public class Circle { private double radius; // other variables and methods } public setRadius(int radius){ if (radius <= 0) throw new IllegalArgumentException ("radius must be > 0. " + "Value of radius: " + radius); this.radius = radius; // other unrelated code } Computer Science II 28

  29. Errors An error is an object of class Error. Similar to an unchecked exception. Need not catch or declare in throws clause. Object of class Error generated when abnormal conditions occur. Errors are more or less beyond your control. Require change of program to resolve. Computer Science II 29

  30. Question 1 What is output by the method badUse if it is called with the following code? int[] nums = {3, 2, 6, 1}; badUse( nums ); public static void badUse(int[] vals){ int total = 0; try{ for(int i = 0; i < vals.length; i++){ int index = vals[i]; total += vals[index]; } } catch(Exception e){ total = -1; } System.out.println(total); } A. 12 B. 0 C. 3 D. -1 E. 5 Computer Science II 30

  31. Question 1 What is output by the method badUse if it is called with the following code? int[] nums = {3, 2, 6, 1}; badUse( nums ); public static void badUse(int[] vals){ int total = 0; try{ for(int i = 0; i < vals.length; i++){ int index = vals[i]; total += vals[index]; } } catch(Exception e){ total = -1; } System.out.println(total); } A. 12 B. 0 C. 3 D. -1 E. 5 Computer Science II 31

  32. Question 2 Is the use of a try-catch block on the previous question a proper use of try- catch blocks? A. Yes B. No Computer Science II 32

  33. Question 2 Is the use of a try-catch block on the previous question a proper use of try-catch blocks? A. Yes B. No What is a better way to handle this type of error? Computer Science II 33

  34. Advantages of Exceptions Separates Exception-Handling Code from "Regular" Code Means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. Propagating Exceptions Down the Call Stack Ability to propagate error reporting down the call stack of methods. Grouping and Differentiating Error Types Since all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy. Computer Science II 34

  35. Computer Science II 35

  36. Creating Exceptions All exceptions must inherit from the Throwable class. If you want to write a checked exception, extend the Exception class. If you want to write an unchecked exception, extend the RuntimeException class. Define at least two constructors: 1. Default, no parameters. 2. Another with String parameter representing a message. For both, call constructor of base class. Do not override inherited getMessage. Computer Science II 36

  37. ExampleCreating Exceptions // File Name MyException.java import java.io.*; public class MyException extends Exception { public MyException(String msg) { super(msg); } } Computer Science II 37

  38. Assertions Statements in the program declaring a Boolean expression about the current state of variables If evaluate to true, nothing happens If evaluate to false, an AssertionError exception is thrown Can be disabled during runtime without program modification or recompilation Two forms assert condition; assert condition: expression; Computer Science II 38

  39. Error Handling, Error Handling Everywhere! Seems like a lot of choices for error prevention and error handling normal program logic (e.g. ifs, for-loop counters) assertions try-catch block When is it appropriate to use each kind? Computer Science II 39

  40. Error Prevention Use program logic (ifs , fors) to prevent logic errors and unchecked exceptions dereferencing a null pointer going outside the bounds of an array violating the preconditions of a method you are calling Computer Science II 40

  41. Error Prevention contd In general, don t use asserts to check preconditions Standard Java style is to use exceptions Use try-catch blocks on checked exceptions Don t use them to handle unchecked exceptions, like null pointer or array index out of bounds One place it is reasonable to use try- catch is in testing suites. put each test in a try-catch. If an exception occurs that test fails, but other tests can still be run Computer Science II 41

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#