+ All Categories
Home > Documents > Object Oriented Programming (OOP)

Object Oriented Programming (OOP)

Date post: 16-Oct-2021
Category:
Upload: others
View: 7 times
Download: 0 times
Share this document with a friend
48
Object Oriented Programming (OOP) Lecture5: Exception Handling & JavaDocs Prepared by: Mohamed Mabrouk Those slides are based on slides by: Dr. Sherin Mousa and Dr. Sally Saad
Transcript
Page 1: Object Oriented Programming (OOP)

Object Oriented Programming (OOP)

Lecture5: Exception Handling & JavaDocs

Prepared by:Mohamed Mabrouk

Those slides are based on slides by:Dr. Sherin Mousa and Dr. Sally Saad

Page 2: Object Oriented Programming (OOP)

Lecture Outline

• What exceptions are• Exception handling• try-catch & try-catch-finally• Throwing exceptions• User defined exceptions• JavaDocs

2

Page 3: Object Oriented Programming (OOP)

Exceptions

3

Page 4: Object Oriented Programming (OOP)

Exceptions• According to Oracle an exception is defined as:

“An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.”

• “When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.”

4

Page 5: Object Oriented Programming (OOP)

Exceptions

• In other words, an exception is a problem/error that occurs during the normal flow of a program

• It causes the normal flow to get disrupted and the program terminates abnormally, unless there is an exception handling block to help handling it gracefully à Exception handling

5

Page 6: Object Oriented Programming (OOP)

Exceptions

• Can you think of some exceptions???

6

Page 7: Object Oriented Programming (OOP)

Exceptions

• Following is just a couple of exceptions defined in Java:• ArithmeticException

• ArrayIndexOutOfBounds-Exception

• FileNotFoundException

• NullPointerException

7

Page 8: Object Oriented Programming (OOP)

Exception Handling• Letting a program terminate abnormally is

considered a bad practice• Rather, exceptions should be handled gracefully,

in order to:• Try to recover;• Retry operation;• Displaying meaningful error;• Terminating the whole program but in a better

way.8

Page 9: Object Oriented Programming (OOP)

Exception Handling Example

9

public float divide(int dividend, int divisor){ return dividend/divisor;

}

Page 10: Object Oriented Programming (OOP)

Exception Handling Example

10

• What if divisor is zero?

public float divide(int dividend, int divisor){ return dividend/divisor;

}

Page 11: Object Oriented Programming (OOP)

Exception Handling Example

11

• What if divisor is zero? à a division by zero error should occur

public float divide(int dividend, int divisor){ return dividend/divisor;

}

Page 12: Object Oriented Programming (OOP)

Exception Handling Example

12

• What if divisor is zero? à a division by zero error should occ

• This would lead to an ArithmeticException

public float divide(int dividend, int divisor){ return dividend/divisor;

}

Page 13: Object Oriented Programming (OOP)

Exception Handling Example

13

public float divide(int dividend, int divisor){ try {

return dividend / divisor;} catch (ArithmeticException exp){

System.out.println("Invalid division"); return -1F;

}}

Page 14: Object Oriented Programming (OOP)

Exception Handling Example

14

public void displayArrayItem(int[] arr, int index){ System.out.println(arr[index]);

}

Page 15: Object Oriented Programming (OOP)

Exception Handling Example

15

What if index is -1, or >= size???

public void displayArrayItem(int[] arr, int index){ System.out.println(arr[index]);

}

Page 16: Object Oriented Programming (OOP)

Exception Handling Example

16

What if index is -1, or >= size???In that case an exception of type ArrayIndexOutOfBoundsException is thrown

public void displayArrayItem(int[] arr, int index){ System.out.println(arr[index]);

}

Page 17: Object Oriented Programming (OOP)

Exception Handling Example

17

public void displayArrayItem(int[] arr, int index){ try {

System.out.println(arr[index]);} catch (ArrayIndexOutOfBoundsException exp){

System.out.println("Invalid index");}

}

Page 18: Object Oriented Programming (OOP)

Exception Handling Example

18

In that case the program will terminate gracefully and displays an indicative error message

public void displayArrayItem(int[] arr, int index){ try {

System.out.println(arr[index]);} catch (ArrayIndexOutOfBoundsException exp){

System.out.println("Invalid index");}

}

Page 19: Object Oriented Programming (OOP)

Types of Exceptions

• There are two types of exceptions• Checked exceptions• Unchecked exceptions

19

Page 20: Object Oriented Programming (OOP)

Checked Exceptions• Checked exceptions are the ones that the program

should anticipate and handle• They are checked at compile time à you MUST

handle them, otherwise you get a compilation error• You have to handle them using try-catch or try-catch-finally

• MUST EXTEND Throwable class either directly or indirectly

• Examples are; FileNotFoundException, and PrinterException

20

Page 21: Object Oriented Programming (OOP)

Unchecked Exceptions• Unchecked exceptions are exceptions that occur outside the

program• Most of the time cannot be expected or recovered from• They are not checked at compile time à you MAY, or MAY NOT

handle them. • No compilation error if not handled• You can handle them using try-catch or try-catch-finally• MUST EXTEND RuntimeException class either directly or indirectly• Examples are; NullPointerException, and ClassCastException

21

Page 22: Object Oriented Programming (OOP)

Exception Hierarchy

22

Page 23: Object Oriented Programming (OOP)

Exception Example

23

public void writeArrayItemsToFile(int[] arr, int length){ PrintWriter printWriter = new PrintWriter(new FileWriter(”E:/input.txt"));for (int i = 0; i < length; i++) {

printWriter.write(arr[i] + "\t");}printWriter.close();

}

Page 24: Object Oriented Programming (OOP)

Exception Example

24

• Two types of exceptions can be thrown here; IOException and ArrayIndexOutOfBoundsException

public void writeArrayItemsToFile(int[] arr, int length){ PrintWriter printWriter = new PrintWriter(new FileWriter(”E:/input.txt"));for (int i = 0; i < length; i++) {

printWriter.write(arr[i] + "\t");}printWriter.close();

}

Page 25: Object Oriented Programming (OOP)

Exception Example

25

• Compiler will prompt you about IOExceptiononly

• Why???

Page 26: Object Oriented Programming (OOP)

Exception Example

26

• Compiler will prompt you about IOExceptiononly

• Why??? à IOException is a checked exception while ArrayIndexOutOfBoundsException is not

• In order to resolve that error, this code fragment should be enclosed in a try-catchblock

Page 27: Object Oriented Programming (OOP)

Exception Example

27

public void writeArrayItemsToFile(int[] arr, int length){try{

PrintWriter printWriter = new PrintWriter(new FileWriter(”E:/input.txt"));for (int i = 0; i < length; i++) {

printWriter.write(arr[i] + "\t");}printWriter.close();

} catch(IOException exp){System.out.println(exp.getMessage());

}}

Page 28: Object Oriented Programming (OOP)

Exception Example

28• There is one minor problem with that code, can

you spot it???

public void writeArrayItemsToFile(int[] arr, int length){try{

PrintWriter printWriter = new PrintWriter(new FileWriter(”E:/input.txt"));for (int i = 0; i < length; i++) {

printWriter.write(arr[i] + "\t");}printWriter.close();

} catch(IOException exp){System.out.println(exp.getMessage());

}}

Page 29: Object Oriented Programming (OOP)

Multiple Catch Blocks

29

• Sometimes a code block may throw several types of exceptions à multiple catch blocks are required

Page 30: Object Oriented Programming (OOP)

Multiple Catch Blocks

30

• Sometimes a code block may throw several types of exception à multiple catch blocks are required

try{....

} catch(IOException exp){System.out.println(exp.getMessage());

} catch(ArithmaticException exp){System.out.println(exp.getMessage());

} catch(Exception exp){System.out.println(exp.getMessage());

}

Page 31: Object Oriented Programming (OOP)

Catching All Exceptions

31

• Since all exceptions extend class Exception, if there is a catch block for Exception, then all exceptions will be caught by that catch block

• The exceptions should be ordered from the very special to the very general à Exceptionclass MUST BE placed at the very end

Page 32: Object Oriented Programming (OOP)

Finally Block

32

• finally block is the last part of try-catch-finally block

• It always gets executed regardless of whether an exception is thrown or not

Page 33: Object Oriented Programming (OOP)

Finally Example

33

• Moving back to that example à can we improve it

public void writeArrayItemsToFile(int[] arr, int length){try{

PrintWriter printWriter = new PrintWriter(new FileWriter(”E:/input.txt"));for (int i = 0; i < length; i++) {

printWriter.write(arr[i] + "\t");}printWriter.close();

} catch(IOException exp){System.out.println(exp.getMessage());

}}

Page 34: Object Oriented Programming (OOP)

Finally Example

34

• What if an exception is thrown, will the PrintWriter get closed?

Page 35: Object Oriented Programming (OOP)

Finally Example

35

• What if an exception is thrown, will the PrintWriter get closed?

• The answer is NO• The PrintWriter will never get closed

reserving unwanted memory• In that case, we can use finally block• finally block will get executed regardless of

whether there is an exception or not

Page 36: Object Oriented Programming (OOP)

Finally Example

36

public void writeArrayItemsToFile(int[] arr, int length){PrintWriter printWriter = null;try{

printWriter = new PrintWriter(new FileWriter(”E:/input.txt"));for (int i = 0; i < length; i++) {

printWriter.write(arr[i] + "\t");}

} catch(IOException exp){System.out.println(exp.getMessage());

} finally { if(printWriter!=null) {

printWriter.close(); }

}}

Page 37: Object Oriented Programming (OOP)

Throwing an Exception

37

• If in your method, there is a critical error that you need to notify about à you can throw an exception

• You may throw one of those:• one of Java standard exceptions, e.g. ArithmaticException

• define your own exception class (user defined exception)

• In order to declare that a method throws and exception, you can use throws keyword

Page 38: Object Oriented Programming (OOP)

User Defined Exception

38

• Let’s think of a simple calculator, what happens if the numbers are very large?

• We need all numbers to be between 1 and 100, otherwise an exception is thrown

Page 39: Object Oriented Programming (OOP)

User Defined Exception Example

39

public class NumberRangeException extends Exception { public NumberRangeException(int lowerBound, int upperBound){ super("The number must be between " + lowerBound + " and " + upperBound); }

}

Page 40: Object Oriented Programming (OOP)

User Defined Exception Example

40

public class NumberRangeException extends Exception { public NumberRangeException(int lowerBound, int upperBound){ super("The number must be between " + lowerBound + " and " + upperBound); }

}

Page 41: Object Oriented Programming (OOP)

User Defined Exception Example

41

public class NumberRangeException extends Exception { public NumberRangeException(int lowerBound, int upperBound){ super("The number must be between " + lowerBound + " and " + upperBound); }

}

public int add(int num1, int num2) throws NumberRangeException{ if(num1 < 1 || num1 > 100 || num2 <1 || num2 > 100){

throw new NumberRangeException(1, 100); } return num1 + num2;

}

Page 42: Object Oriented Programming (OOP)

User Defined Exception Example

42

public class NumberRangeException extends Exception { public NumberRangeException(int lowerBound, int upperBound){ super("The number must be between " + lowerBound + " and " + upperBound); }

}

public int add(int num1, int num2) throws NumberRangeException{ if(num1 < 1 || num1 > 100 || num2 <1 || num2 > 100){

throw new NumberRangeException(1, 100); } return num1 + num2;

}

Page 43: Object Oriented Programming (OOP)

JavaDocs

43

Page 44: Object Oriented Programming (OOP)

What are JavaDocs

44

• JavaDocs are used to document your own code and/or APIs

• This enables other users to understand and use them

• JavaDocs can be generated based on your code

• IDEs, e.g. NetBeans and IntelliJ can help you generate them

Page 45: Object Oriented Programming (OOP)

JavaDocs Format

45

• Once JavaDocs are generated, a couple of HTML files containing documentation are generated

• The classes are grouped by their respective packages

• The documentation has to be enclosed in /** …. */

Page 46: Object Oriented Programming (OOP)

JavaDoc Example

46

/** * This is a simple calculator */public class Calculator {

/** * Adds two numbers and returns their sum * @param num1 First number * @param num2 Second number * @return The sum of the two numbers */ public int add(int num1, int num2){

return num1 + num2; }

}

Page 47: Object Oriented Programming (OOP)

JavaDoc Output

47

Page 48: Object Oriented Programming (OOP)

Thank You!

48


Recommended