CS计算机代考程序代写 chain compiler Java SWEN20003 Object Oriented Software Development

SWEN20003 Object Oriented Software Development

SWEN20003
Object Oriented Software Development

Exceptions

Exceptions SWEN20003 1 / 27

Lecture Objectives

After this lecture you will be able to:

Understand what exceptions are

Appropriately handle exceptions in Java

Define and utilise exceptions in Java

Exceptions SWEN20003 2 / 27

Errors

It is common to make mistakes (errors) while developing as well as typing
a program.

Such mistakes can be categorised as:

Syntax errors

Semantic errors

Runtime errors

Exceptions SWEN20003 3 / 27

Errors

Keyword

Syntax: Errors where what you write isn’t legal code; identified by the
editor/compiler.

Keyword

Semantic: Code runs to completion, but results in incorrect
output/operation; identified through software testing (coming soon).

Keyword

Runtime: An error that causes your program to end prematurely (crash
and burn); identified through execution.

Exceptions SWEN20003 4 / 27

Common Runtime Errors

Dividing a number by zero

Accessing an element that is out of bounds of an array.

Trying to store incompatible data elements.

Using negative value as array size

Trying to convert from string data to another type (e.g., converting
string “abc” to integer value)

File errors:
I opening a file in “read mode” that does not exist or no read permission
I Opening a file in “write/update mode” which has “read only”

permission

Many more …

Exceptions SWEN20003 5 / 27

Runtime Error – Example

class NoErrorHandling {

public static void main(String[] args){

int n1 = 1, n2 = 0;

System.out.println(“The result is ” + divide(n1, n2));

System.out.println(“The program reached this line”);

}

public static int divide(int n1, int n2) {

return n1/n2;

}

}

What happens if n2 == 0?

Exception in thread “main” java.lang.ArithmeticException: …

Solution 1: Do nothing and hope for the best. Obviously less than ideal.

Exceptions SWEN20003 6 / 27

Runtime Errors

How can we protect against the error?

public int divide(int n1, double n2) {

if (n2 != 0) {

return n1/n2;

} else {

???

}

}

if (n2 != 0) {

divide(n1, n2);

} else {

// Print error message and exit or continue

}

Solution 2: Explicitly guard yourself against dangerous or invalid
conditions, known as defensive programming.

Exceptions SWEN20003 7 / 27

Runtime Errors

What are some downsides of solution 2?

Need to explicitly protect against every possible error condition

Some conditions don’t have a “backup” or alternate path, they’re just
failures

Not very nice to read

Poor abstraction (bloated code)

Exceptions SWEN20003 8 / 27

Runtime Errors

class WithExceptionHandling {

public static void main(String[] args){

int n1 = 1, n2 = 0;

try {

System.out.println(“The result is ” + divide(n1, n2));

} catch (ArithmeticException e) {

System.out.println(“Cannot divide – n2 is zero”);

}

System.out.println(“The program reached this line”);

}

public static int divide(int n1, int n2) {

return n1/n2;

}

}

Solution 3: Use exceptions to catch error states, then recover from them,
or gracefully end the program.

Exceptions SWEN20003 9 / 27

Exceptions

Keyword

Exception: An error state created by a runtime error in your code; an
exception.

Keyword

Exception: An object created by Java to represent the error that was
encountered.

Keyword

Exception Handling: Code that actively protects your program in the case
of exceptions.

Exceptions SWEN20003 10 / 27

Exception Handling

public void method(…) {

try {

} catch ( varName) {

} finally {

}

}

Exceptions SWEN20003 11 / 27

Exception Handling

Keyword

try: Attempt to execute some code that may result in an error state
(exception).

Keyword

catch: Deal with the exception. This could be recovery (ask the user to
input again, adjust an index) or failure (output an error message and exit).

Keyword

finally: Perform clean up (like closing files) assuming the code didn’t exit.

Exceptions SWEN20003 12 / 27

Exception Handling

class WithExceptionCatchThrowFinally {

public static void main(String[] args){

int n1 = 1, n2 = 0;

try {

System.out.println(“The result is ” + divide(n1, n2));

} catch (ArithmeticException e) {

System.out.println(“Cannot divide – n2 is zero”);

} finally {

System.out.println(“The program reached this line”);

}

}

public static int divide(int n1, int n2) {

return n1/n2;

}

}

Exceptions SWEN20003 13 / 27

Exception Handling – Chaining Exceptions

public void processFile(String filename) {

try {

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

We can also chain catch blocks to deal with different exceptions
separately. The most “specific” exception (subclasses) come first, with
“broader” exceptions (superclasses) listed lower.

Exceptions SWEN20003 14 / 27

Assess Yourself

Write a method that has the potential to create an
ArithmeticException and an ArrayIndexOutOfBoundException, and
implement appropriate exception handling for these cases.

Exceptions SWEN20003 15 / 27

Assess Yourself

public class AverageDifference {

public static void main(String[] args) {

int[] n1 = {1, 2, 3};

int[] n2 = {2, 3, 4};

try {

System.out.println(“Answer = ” + averageDifference(n1, n2));

} catch (ArithmeticException e) {

System.out.println(“Caught an arithmetic exception”);

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println(“Caught an index exception”);

}

}

public static int averageDifference(int n1[], int n2[]) {

int sumDifference = 0;

for (int i = 0; i < n1.length; i++) { sumDifference += n1[i] - n2[i]; } return sumDifference/n1.length; } } Exceptions SWEN20003 16 / 27 Generating Exceptions Keyword throw: Respond to an error state by creating an exception object, either already existing or one defined by you. Keyword throws: Indicates a method has the potential to create an exception, and can’t be bothered to deal with it (Slick stupidly does this for everything), or that the exact response varies by application. Exceptions SWEN20003 17 / 27 Assess Yourself Write a method that has the potential to create a NullPointerException, and throws an exception if its argument is null. public class Person { private String name; private int age; public Person(int age, String name) throws NullPointerException { if (name == null) { throw new NullPointerException("Creating person with null name"); } this.age = age; this.name = name; } public static void main(String[] args) { Person p1 = new Person(10, "Sarah"); Person p2 = new Person(12, null); } } Exceptions SWEN20003 18 / 27 Defining Exceptions What if we discover a new “type” of problem? We can define our own exceptions! Exceptions are classes! Most exceptions inherit from an Exception class All exceptions should have two constructors, but we can add whatever else we like Exceptions SWEN20003 19 / 27 Assess Yourself Write a class Circle, which has attributes centre and radius, initialized at creation. Your must ensure that the radius is greater than zero. Exceptions SWEN20003 20 / 27 Assess Yourself Step 1: Write the exception class. import java.lang.Exception; public class InvalidRadiusException extends Exception { public InvalidRadiusException() { super("Radius is not valid"); } public InvalidRadiusException(double radius){ super("Radius [" + radius + "] is not valid"); } } Exceptions SWEN20003 21 / 27 Assess Yourself Step 2: Write the Circle class. public class Circle { private double centreX, centreY; private double radius; public Circle (double centreX, double centreY, double radius) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } this.centreX = centreX; this.centreY = centreY; this.radius = radius; } } Exceptions SWEN20003 22 / 27 Assess Yourself Step 3: Test your class. public class TestCircle { public static void main(String[] args) { try { Circle c1 = new Circle(10, 10, 100); System.out.println("Circle 1 created"); Circle c2 = new Circle(10, 10, -1); System.out.println("Circle 2 created"); } catch(InvalidRadiusException e) { System.out.println(e.getMessage()); } } } "Circle 1 created" "Radius [-1] is not valid" Exceptions SWEN20003 23 / 27 Types of Exceptions Keyword Unchecked: Exceptions that are not checked at compile time. The compiler will not give an error if an unchecked exception is not handled. E.g., NullPointerException, ArrayIndexOutOfBound, etc Keyword Checked: Exceptions that are checked at compile time by the compiler. Inherit from the Exception class and are not subclasses of RuntimeException. E.g., IOException, SQLException, ClassNotFoundException, etc. Exceptions SWEN20003 24 / 27 Exception Handling Catch or Declare All checked exceptions must be handled by I Enclosing code that can generate exceptions in a try-catch block I Declaring that a method may create an exception using the throws clause Both techniques can be used in the same method, for different exceptions Using Exceptions Should be reserved for when a method encounters an unusual or unexpected case that cannot be handled easily in some other way Exceptions SWEN20003 25 / 27 Try With public void processFile(String filename) { try (BufferedReader reader = ...) { ... } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } The finally block is used to handle cleanup, but in many cases we can use the try-with notation to handle cleanup automatically. Exceptions SWEN20003 26 / 27 Questions? Exceptions SWEN20003 27 / 27