Chapter I - Overview of Java Programming
Chapter I - Overview of Java Programming
Chapter 1 – Overview of
Java Programming
Data types and
variables
– Programmer error,
85
Sample Program [1] cont.
• Compiles successfully but encounters a problem when it
runs
• ArrayIndexOutOfBoundException is a subclass of
What happens when exception
occurs?
• When an exception occurs within a method, the method creates an
object and hands it off to the runtime system.
The runtime system searches the call stack for a method that
contains a block of code that can handle the exception. This block of
code is called an exception handler.
The search begins with the method in which the error occurred and
proceeds through the call stack in the reverse order in which the methods
were called.
If the runtime system exhaustively searches all the methods on the call
SumNumbers [1]
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i < arguments.length; i++)
sum += Float.parseFloat(arguments[i]);
System.out.println("Those numbers add up to "+
sum);
}
}
89
SumNumbers [2]
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i < arguments.length; i++)
sum += Float.parseFloat(arguments[i]);
System.out.println("Those numbers add up to "+
sum);
}
}
90
Example [1]
import java.util.Scanner;
• Specifying the exception in the method signature: You can declare that a
method throws a checked exception by including the exception type in the
method signature using the "throws" keyword. This means that any code
calling the method must either handle the exception or declare it to be
thrown as well.
public void someMethod() throws
SomeCheckedException {
// Code that may throw a checked
exception
Catching Exceptions in a try-catch
Block
try {
// Code that may throw an exception
} catch (ExceptionType1 ex1) {
// Exception handling for ExceptionType1
} catch (ExceptionType2 ex2) {
// Exception handling for ExceptionType2
} finally {
// Code that is always executed,
// regardless of whether an exception occurred or
not
NewSumNumbers [1]
public class NewSumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i<arguments.length; i++){
try {
sum += Float.parseFloat(arguments[i]);
}
catch (NumberFormatException e) {
System.out.println(arguments[i] + " isn’t a
number.");
}
}
System.out.println("Those numbers add up to "+ sum);
}
}
NewSumNumbers [Output]
Catching Several Different Exceptions
public class DivideNumbers {
public static void main(String[] arguments) {
if (arguments.length == 2) {
int result = 0;
try {
result =
Integer.parseInt(arguments[0])/Integer.parseInt(arguments[1]);
System.out.println("Result = " + result);
}
catch (NumberFormatException e) {
System.out.println("Both arguments must be numbers.");
}
catch (ArithmeticException e) {
System.out.println("You cannot divide by zero");
}
}
}
}
finally : Example
public class ExcepTest {