0% found this document useful (0 votes)
35 views

07 1 Exception Handling

The document discusses exception handling in Java programs. It explains what exceptions are, when they should be used, and how to write code using try, catch, and finally blocks to handle exceptions gracefully so that programs can continue running or terminate properly even if problems occur.

Uploaded by

Nousheen Akhtar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

07 1 Exception Handling

The document discusses exception handling in Java programs. It explains what exceptions are, when they should be used, and how to write code using try, catch, and finally blocks to handle exceptions gracefully so that programs can continue running or terminate properly even if problems occur.

Uploaded by

Nousheen Akhtar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Exception Handling

Dr. Mian M.Hamayun


[email protected]
http://seecs.nust.edu.pk/faculty/mianhamayun.html
» We will learn:
˃ What exceptions are and how they’re handled.
˃ When to use exception handling.
˃ To use try blocks to delimit code in which exceptions might
occur.
˃ To throw exceptions to indicate a problem.
˃ To use catch blocks to specify exception handlers.
˃ To use the finally block to release resources.
˃ The exception class hierarchy.
2
» Exception – an indication of a problem that occurs
during a program’s execution

» Exception handling – resolving exceptions that may


occur so program can continue or terminate gracefully

» Exception handling enables programmers to create


programs that are more robust and fault-tolerant
3
» ArrayIndexOutOfBoundsException – an attempt
is made to access an element past the end of an array

» ClassCastException – an attempt is made to cast


an object that does not have an is-a relationship with
the type specified in the cast operator

» NullPointerException – when a null reference is


used where an object is expected
4
» Intermixing program logic with error-handling logic
can make programs difficult to read, modify, maintain
and debug

» Exception handling enables programmers to remove


error-handling code from the “main line” of the
program’s execution

» Improves clarity
5

» Enhances modifiability
» ArithmeticException – can arise from a number
of different problems in arithmetic

» InputMismatchException – occurs when Scanner


method nextInt receives a string that does not
represent a valid integer
6
1 // Fig. 13.1: DivideByZeroNoExceptionHandling.java 7
2 // An application that attempts to divide by zero.
3 import java.util.Scanner;
4 Attempt to divide; denominator
5 public class DivideByZeroNoExceptionHandling
may be zero
6 {
7 // demonstrates throwing an exception when a divide-by-zero occurs
8 public static int quotient( int numerator, int denominator )
9 {
10 return numerator / denominator; // possible division by zero
11 } // end method quotient
12
13 public static void main( String args[] )
14 {
15 Scanner scanner = new Scanner( System.in ); // scanner for input
16
17 System.out.print( "Please enter an integer numerator: " );
18 int numerator = scanner.nextInt(); Read input; exception occurs if
19 System.out.print( "Please enter an integer denominator: " );
input is not a valid integer
20 int denominator = scanner.nextInt();
21
22 int result = quotient( numerator, denominator );
23 System.out.printf(
24 "\nResult: %d / %d = %d\n", numerator, denominator, result );
25 } // end main
26 } // end class DivideByZeroNoExceptionHandling

Please enter an integer numerator: 100


Please enter an integer denominator: 7
7

Result: 100 / 7 = 14
Please enter an integer numerator: 100
Please enter an integer denominator: 7

Result: 100 / 7 = 14

Please enter an integer numerator: 100


Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at
DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:10)
at
DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:22)

Please enter an integer numerator: 100


Please enter an integer denominator: hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at
DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:20)
8
» Thrown exception – an exception that has occurred

» Stack trace
˃ Name of the exception in a descriptive message that
indicates the problem
˃ Complete method-call stack

» Throw point – initial point at which the exception


occurs, top row of call chain
9
» With exception handling, the program catches and
handles (i.e., deals with) the exception

» Next example allows user to try again if invalid input is


entered (zero for denominator, or non-integer input)
10
1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java
2 // An exception-handling example that checks for divide-by-zero. 11
3 import java.util.InputMismatchException;
4 import java.util.Scanner; throws clause specifies that
5 method quotient may throw
6 public class DivideByZeroWithExceptionHandling
7 {
an ArithmeticException
8 // demonstrates throwing an exception when a divide-by-zero occurs
9 public static int quotient( int numerator, int denominator )
10 throws ArithmeticException
11 {
12 return numerator / denominator; // possible division by zero
13 } // end method quotient
14 Repetition statement loops until try
15 public static void main( String args[] ) block completes successfully
16 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input
18 boolean continueLoop = true; // determines if more input is needed
19
20 do try block attempts to read
21 {
22 try // read two numbers and calculate quotient
input and perform division
23 {
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " );
27 int denominator = scanner.nextInt();
28 Retrieve input;
11

InputMismatchException
thrown if input not valid integers
Call method quotient,
Catching InputMismatchException
which may throw
(user has entered non-integer input)
ArithmeticException
29 int result = quotient( numerator, denominator );
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator, 12
If we have reached this point,
31 denominator, result ); input was valid and
32 continueLoop = false; // input successful; end looping
33 } // end try
denominator was non-
34 catch ( InputMismatchException inputMismatchException ) zero, so looping can stop
35 {
36 System.err.printf( "\nException: %s\n",
37 inputMismatchException ); Exception parameters
38 scanner.nextLine(); // discard input so user can try again
39 System.out.println(
40 Read invalid input but do nothing with it
"You must enter integers. Please try again.\n" );
41 } // end catch
42 catch ( ArithmeticException arithmeticException ) Notify user of error made
43 {
44 System.err.printf( "\nException: %s\n", arithmeticException );
45 System.out.println(
46 "Zero is an invalid denominator. Please try again.\n" );
47 } // end catch
48 } while ( continueLoop ); // end do...while Catching ArithmeticException
49 } // end main
50 } // end class DivideByZeroWithExceptionHandling
(user has entered zero for denominator)
12

If line 32 was never successfully reached,


loop continues and user can try again
Please enter an integer numerator: 100
Please enter an integer denominator: 7

Result: 100 / 7 = 14

Please enter an integer numerator: 100


Please enter an integer denominator: 0

Exception: java.lang.ArithmeticException: / by zero


Zero is an invalid denominator. Please try again.

Please enter an integer numerator: 100


Please enter an integer denominator: 7

Result: 100 / 7 = 14

Please enter an integer numerator: 100


Please enter an integer denominator: hello

Exception: java.util.InputMismatchException
You must enter integers. Please try again.

Please enter an integer numerator: 100


Please enter an integer denominator: 7

Result: 100 / 7 = 14
13
» try block – encloses code that might throw an
exception and the code that should not execute if an
exception occurs

» Consists of keyword try followed by a block of code


enclosed in curly braces

» try statement – consists of try block and


corresponding catch and/or finally blocks
14
Exceptions may surface:
» through explicitly mentioned code in a try block,
» through calls to other methods,
» through deeply nested method calls initiated by code in a try
block,
» or from the Java Virtual Machine as it executes Java bytecodes.
15
» catch block – catches (i.e., receives) and handles an
exception, contains:
˃ Begins with keyword catch
˃ Exception parameter in parentheses – exception parameter identifies
the exception type and enables catch block to interact with caught
exception object
˃ Block of code in curly braces that executes when exception of proper
type occurs
» Matching catch block – the type of the exception
parameter matches the thrown exception type exactly
or is a superclass of it
» Uncaught exception – an exception that occurs for
which there are no matching catch blocks
˃ Cause program to terminate if program has only one thread; Otherwise
only current thread is terminated and there may be adverse effects to
16

the rest of the program


It is a syntax error to place code between a try block
and its corresponding catch blocks.
It is a compilation error to catch the same type in two
different catch blocks in a single try statement.
17
» When an exception occurs:
˃ try block terminates immediately
˃ Program control transfers to the first matching catch block

» After exception is handled:


˃ Termination model of exception handling – program control
does not return to the throw point because the try block
has expired; flow of control proceeds to the first statement
after the last catch block
˃ Resumption model of exception handling – program control
resumes just after throw point (in some other languages)
18
» throws clause – specifies the exceptions a method
may throws
˃ Appears after method’s parameter list and before the
method’s body

˃ Contains a comma-separated list of exceptions

˃ Exceptions can be thrown by statements in method’s body


or by methods called in method’s body

˃ Exceptions can be of types listed in throws clause or


subclasses
19
1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java
2 // An exception-handling example that checks for divide-by-zero.
3 import java.util.InputMismatchException;
4 import java.util.Scanner;
5
6 public class DivideByZeroWithExceptionHandling
7 {
8 // demonstrates throwing an exception when a divide-by-zero occurs
9 public static int quotient( int numerator, int denominator )
10 throws ArithmeticException
11 {
12 return numerator / denominator; // possible division by zero
13 } // end method quotient
14
15 public static void main( String args[] )
16 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input
18 boolean continueLoop = true; // determines if more input is needed
19
20 do
21 {
22 try // read two numbers and calculate quotient
23 {
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " );
27 int denominator = scanner.nextInt();
28
20
If you know that a method might throw an exception,
include appropriate exception-handling code in your
program to make it more robust.
Read the online API documentation for a method
before using that method in a program. The
documentation specifies the exceptions thrown by
the method (if any) and indicates reasons why such
exceptions may occur. Then provide code for handling
those exceptions in your program.
Read the online API documentation for an exception
class before writing exception-handling code for that
type of exception.
21
» Exception handling is designed to process synchronous
errors

» Synchronous errors – occur when a statement


executes

» Asynchronous errors – occur in parallel with and


independent of the program’s flow of control (e.g.,
network message arrivals, mouse clicks and
keystrokes, etc.)
22
Exception handling provides a single, uniform technique
for processing problems. This helps programmers
working on large projects understand each other’s error-
processing code.
23
24
» All exceptions inherit either directly or indirectly from
class Exception
» Exception classes form an inheritance hierarchy that
can be extended
» Class Throwable, superclass of Exception
˃ Only Throwable objects can be used with the exception-
handling mechanism
˃ Has two subclasses: Exception and Error
+ Class Exception and its subclasses represent exception situations
that can occur in a Java program and that can be caught by the
application
+ Class Error and its subclasses represent abnormal situations that
could happen in the JVM – it is usually not possible for a program to
recover from Errors
25
» Two categories of exceptions: checked and unchecked
» Checked exceptions
˃ Exceptions that inherit from class Exception but not from
RuntimeException
˃ Compiler enforces a catch-or-declare requirement
˃ Compiler checks each method call and method declaration to determine
whether the method throws checked exceptions. If so, the compiler
ensures that the checked exception is caught or is declared in a throws
clause. If not caught or declared, compiler error occurs.
» Unchecked exceptions
˃ Inherit from class RuntimeException or class Error
˃ Compiler does not check code to see if exception is caught or declared
˃ If an unchecked exception occurs and is not caught, the program
terminates or runs with unexpected results
˃ Can typically be prevented by proper coding
26
Programmers are forced to deal with checked
exceptions. This results in more robust code than would
be created if programmers were able to simply ignore
the exceptions.
27
» A compilation error occurs if a method explicitly
attempts to throw a checked exception (or calls
another method that throws a checked exception) and
that exception is not listed in that method’s throws
clause.
» If a subclass method overrides a superclass method, it
is an error for the subclass method to list more
exceptions in its throws clause than the overridden
superclass method does. However, a subclass’s
throws clause can contain a subset of a superclass’s
throws list.
28
» If your method calls other methods that explicitly throw
checked exceptions, those exceptions must be caught or
declared in your method. If an exception can be handled
meaningfully in a method, the method should catch the
exception rather than declare it.
» Although the compiler does not enforce the catch-or-
declare requirement for unchecked exceptions, provide
appropriate exception-handling code when it is known that
such exceptions might occur. For example, a program
should process the NumberFormatException from
Integer method parseInt, even though
NumberFormatException (a subclass of
RuntimeException) is an unchecked exception type.
29

This makes your programs more robust.


» catch block catches all exceptions of its type and
subclasses of its type
» If there are multiple catch blocks that match a
particular exception type, only the first matching
catch block executes
» It makes sense to use a catch block of a superclass
when all the catch blocks for that class’s subclasses
will perform the same functionality
30
» Catching subclass types individually is subject to error
if you forget to test for one or more of the subclass
types explicitly; catching the superclass guarantees
that objects of all subclasses will be caught.
» Positioning a catch block for the superclass type after
all other subclass catch blocks for subclasses of that
superclass ensures that all subclass exceptions are
eventually caught.
31
» Placing a catch block for a superclass exception type
before other catch blocks that catch subclass
exception types prevents those blocks from executing,
so a compilation error occurs.
32
» Programs that obtain certain resources must return
them explicitly to avoid resource leaks
» finally block
˃ Consists of finally keyword followed by a block of code
enclosed in curly braces
˃ Optional in a try statement
˃ If present, is placed after the last catch block
˃ Executes whether or not an exception is thrown in the
corresponding try block or any of its corresponding catch
blocks
˃ Will not execute if the application exits early from a try
block via method System.exit
˃ Typically contains resource-release code
33
» A subtle issue is that Java does not entirely eliminate
memory leaks. Java will not garbage collect an object
until there are no more references to it. Thus, memory
leaks can occur, if programmers erroneously keep
references to unwanted objects.
34
try
{
statements
resource-acquisition statements
} // end try

catch ( AKindOfException exception1 )


{
exception-handling statements
} // end catch
.
.
.

catch ( AnotherKindOfException exception2 )


{
exception-handling statements
} // end catch

finally
{
statements
resource-release statements
} // end finally

Fig. 2 | Position of the finally block after the last catch block in a try statement.
35
» If no exception occurs, catch blocks are skipped and
control proceeds to finally block.
» After the finally block executes control proceeds to
first statement after the finally block.
» If exception occurs in the try block, program skips
rest of the try block. First matching the catch block
executes and control proceeds to the finally block.
If exception occurs and there are no matching catch
blocks, control proceeds to the finally block. After
the finally block executes, the program passes the
exception to the next outer the try block.
» If catch block throws an exception, the finally
36

block still executes.


» Always release each resource explicitly and at the
earliest possible moment at which the resource is no
longer needed. This makes resources immediately
available to be reused by your program or by other
programs, thus improving resource utilization. Because
the finally block is guaranteed to execute whether
or not an exception occurs in the corresponding try
block, this block is an ideal place to release resources
acquired in a try block.
37
» Standard streams
˃ System.out – standard output stream
˃ System.err – standard error stream

» System.err can be used to separate error output


from regular output

» System.err.println and System.out.println


display data to the command prompt by default
38
» throw statement – used to throw exceptions
» Programmers can throw exceptions themselves from a
method if something has gone wrong
» throw statement consists of keyword throw followed
by the exception object
39
» An object can be thrown without containing
information about the problem that occurred. In this
case, simple knowledge that an exception of a
particular type occurred may provide sufficient
information for the handler to process the problem
correctly.
» Exceptions can be thrown from constructors. When an
error is detected in a constructor, an exception should
be thrown rather than creating an improperly formed
object.
40
» Exceptions are rethrown when a catch block decides
either that it cannot process the exception or that it
can only partially process it

» Exception is deferred to outer try statement

» Exception is rethrown by using keyword throw


followed by a reference to the exception object
41
» If an exception has not been caught when control
enters a finally block and the finally block
throws an exception that is not caught in the finally
block, the first exception will be lost and the exception
from the finally block will be returned to the calling
method.
» Avoid placing code that can throw an exception in a
finally block. If such code is required, enclose the
code in a try statement within the finally block.
42
» Java’s exception-handling mechanism is intended to
remove error-processing code from the main line of a
program’s code to improve program clarity. Do not
place try... catch finally... around every
statement that may throw an exception. This makes
programs difficult to read. Rather, place one try block
around a significant portion of your code, follow that
try block with catch blocks that handle each
possible exception and follow the catch blocks with a
single finally block (if one is required).
43
1 // Fig. 13.5: UsingExceptions.java
2 // Demonstration of the try...catch...finally exception handling
3 // mechanism.
4
5 public class UsingExceptions
6 {
7 public static void main( String args[] )
8 {
9 try
10 {
11 throwException(); // call method throwException
12 } // end try
13 catch ( Exception exception ) // exception thrown by throwException
Call method that throws an exception
14 {
15 System.err.println( "Exception handled in main" );
16 } // end catch
17
18 doesNotThrowException();
19 } // end main
20
44
21 // demonstrate try...catch...finally
22 public static void throwException() throws Exception
23 {
24 try // throw an exception and immediately catch it
25 {
26 System.out.println( "Method throwException" );
27 throw new Exception(); // generate exception
28 } // end try
29 catch ( Exception exception ) // catch exception thrown in try
30 {
31 System.err.println(
Create new Exception and throw it
32 "Exception handled in method throwException" );
33 throw exception; // rethrow for further processing
34
35 // any code here would not be reached Throw previously created Exception
36
37 } // end catch
38 finally // executes regardless of what occurs in try...catch
39 {
40 System.err.println( "Finally executed in throwException" );
41 } // end finally
finally block executes even though
42 exception is rethrown in catch block
43 // any code here would not be reached, exception rethrown in catch
45

44
45 } // end method throwException
46
47 // demonstrate finally when no exception occurs
48 public static void doesNotThrowException()
49 {
50 try // try block does not throw an exception
51 {
52 System.out.println( "Method doesNotThrowException" );
53 } // end try
54 catch ( Exception exception ) // does not execute
55 {
56 System.err.println( exception );
57 } // end catch
58 finally // executes regardless of what occurs in try...catch
59 {
60 System.err.println(
61
finally block executes even
"Finally executed in doesNotThrowException" );
62 } // end finally though no exception is thrown
63
64 System.out.println( "End of method doesNotThrowException" );
65 } // end method doesNotThrowException
66 } // end class UsingExceptions

Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
46

End of method doesNotThrowException


» Stack unwinding – When an exception is thrown but
not caught in a particular scope, the method-call stack
is “unwound,” and an attempt is made to catch the
exception in the next outer try block.
» When unwinding occurs:
˃ The method in which the exception was not caught
terminates
˃ All local variables in that method go out of scope
˃ Control returns to the statement that originally invoked the
method – if a try block encloses the method call, an attempt
is made to catch the exception.
47
1 // Fig. 13.6: UsingExceptions.java
2 // Demonstration of stack unwinding.
3
4 public class UsingExceptions
5 {
6 public static void main( String args[] )
7 {
8 try // call throwException to demonstrate stack unwinding
9 { Call method that throws an exception
10 throwException();
11 } // end try
12 catch ( Exception exception ) // exception thrown in throwException
13 {
14 System.err.println( "Exception handled in main" );
15 } // end catch
16 } // end main
17 Catch exception that may occur in the
above try block, including the call
to method throwException
48
18 // throwException throws exception that is not caught in this method
19 public static void throwException() throws Exception
20 {
21 try // throw an exception and catch it in main Method throws exception
22 {
23 System.out.println( "Method throwException" );
24 throw new Exception(); // generate exception
25 } // end try
26 Throw new exception; Exception not
catch ( RuntimeException runtimeException ) // catch incorrect type
27 { caught in current try block, so
28 System.err.println(
29 "Exception handled in method throwException" );
handled in outer try block
30 } // end catch
31 finally // finally block always executes finally block executes before
32 { control returns to outer try block
33 System.err.println( "Finally is always executed" );
34 } // end finally
35 } // end method throwException
36 } // end class UsingExceptions

Method throwException
Finally is always executed
Exception handled in main
49
» An exception that is not caught in an application
causes Java’s default exception handler to run. This
displays the name of the exception, a descriptive
message that indicates the problem that occurred and
a complete execution stack trace.
» Throwable method toString (inherited by all
Throwable subclasses) returns a string containing the
name of the exception’s class and a descriptive
message.
50
Never ignore an exception you catch. At least use
printStackTrace to output an error message. This
will inform users that a problem exists, so that they can
take appropriate actions.
51
» Chained exceptions enable an exception object to
maintain the complete stack-trace information when
an exception is thrown from a catch block

» Users can retrieve information about original


exception

» Stack trace from a chained exception displays how


many chained exceptions remain
52
1 // Fig. 13.8: UsingChainedExceptions.java
2 // Demonstrating chained exceptions.
3
4 public class UsingChainedExceptions
5 {
6 public static void main( String args[] )
7 {
8 try
9 { Catch exception from method1 as well
10 method1(); // call method1 as any associated chained exceptions
11 } // end try
12 catch ( Exception exception ) // exceptions thrown from method1
13 {
14 exception.printStackTrace();
15 } // end catch
16 } // end main
17
53
18 // call method2; throw exceptions back to main
19 public static void method1() throws Exception
20 {
21 try
22 { Catch exception from method2, throw new
23 method2(); // call method2 exception to be chained with earlier exceptions
24 } // end try
25 catch ( Exception exception ) // exception thrown from method2
26 {
27 throw new Exception( "Exception thrown in method1", exception );
28 } // end try
29 } // end method method1
30
31 // call method3; throw exceptions back to method1
32 public static void method2() throws Exception
33 {
34 try
35 { Catch exception from method3, throw new
36 method3(); // call method3 exception to be chained with earlier exceptions
37 } // end try
38 catch ( Exception exception ) // exception thrown from method3
39 {
40 throw new Exception( "Exception thrown in method2", exception );
41 } // end catch
42 } // end method method2
43
54
44 // throw Exception back to method2
45 public static void method3() throws Exception
46 {
47 throw new Exception( "Exception thrown in method3" );
48 } // end method method3
49 } // end class UsingChainedExceptions
Original thrown exception
java.lang.Exception: Exception thrown in method1
at UsingChainedExceptions.method1(UsingChainedExceptions.java:27)
at UsingChainedExceptions.main(UsingChainedExceptions.java:10)
Caused by: java.lang.Exception: Exception thrown in method2
at UsingChainedExceptions.method2(UsingChainedExceptions.java:40)
at UsingChainedExceptions.method1(UsingChainedExceptions.java:23)
... 1 more
Caused by: java.lang.Exception: Exception thrown in method3
at UsingChainedExceptions.method3(UsingChainedExceptions.java:47)
at UsingChainedExceptions.method2(UsingChainedExceptions.java:36)
... 2 more
55
» Preconditions and postconditions are the states before
and after a method’s execution

» Used to facilitate debugging and improve design

» You should state the preconditions and postconditions


in a comment before the method declaration
56
» Preconditions
˃ Condition that must be true when the method is invoked
˃ Describe method parameters and any other expectations
the method has about the current state of a program
˃ If preconditions not met, method’s behavior is undefined
» Postconditions
˃ Condition that is true after the method successfully returns
˃ Describe the return value and any other side-effects the
method may have
˃ When calling a method, you may assume that a method
fulfills all of its postconditions
57
» Assertions are conditions that should be true at a
particular point in a method
» Help ensure a program’s validity by catching potential
bugs
» Preconditions and Postconditions are two kinds of
assertions
» Assertions can be stated as comments or assertions
can be validated programmatically using the assert
statement
58
» assert statement
˃ Evaluates a boolean expression and determines whether it
is true or false
˃ Two forms
+ assert expression; -- AssertionError is thrown if expression is
false
+ assert expression1 : expression2; -- AssertionError is thrown if
expression1 is false, expression2 is error message
˃ Used to verify intermediate states to ensure code is working
correctly
˃ Used to implement preconditions and postconditions
programmatically
» By default, assertions are disabled
» Assertions can be enabled with the –ea command-line
59

option
1 // Fig. 13.9: AssertTest.java
2 // Demonstrates the assert statement
3 import java.util.Scanner;
4
5 public class AssertTest
6 {
7 public static void main( String args[] )
8 {
9 Scanner input = new Scanner( System.in );
10
11 System.out.print( "Enter a number between 0 and 10: " );
12 int number = input.nextInt(); Message to be displayed with
13 assert statement AssertionError
14 // assert that the absolute value is >= 0
15 assert ( number >= 0 && number <= 10 ) : "bad number: " + number;
16
17 System.out.printf( "You entered %d\n", number );
18 } // end main
If number is less than 0 or greater than
19 } // end class AssertTest 10, AssertionError occurs
Enter a number between 0 and 10: 5
You entered 5

Enter a number between 0 and 10: 50


Exception in thread "main" java.lang.AssertionError: bad number: 50
at AssertTest.main(AssertTest.java:15)
60
61

You might also like