lecture 22

21
Lecture-22 Instructor Name: Object Oriented Programming

Upload: talha-ijaz

Post on 14-Apr-2017

134 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Lecture 22

Lecture-22Instructor Name:

Object Oriented Programming

Page 2: Lecture 22

Today’s Lecture

User Defined Exceptions

Assertion Statement

2

Page 3: Lecture 22

User Defined Exception

What is User Defined Exception? User-defined exception class is used to show custom

messages to the end users.

It is used to hide the other exceptions like null pointer exception; arithmetic exception etc.

User-defined exception class is so common that it will be used in every project.

Only one step will be enough to create user-defined exception class i.e. extend the Exception class.

3

Page 4: Lecture 22

User Defined Exception

Key Points Keep the following points in mind when writing your

own exception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is

automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.

4

Page 5: Lecture 22

User Defined Exception

Syntax We can define our own Exception class as below:

class MyException extends Exception{ . . . . .

}

5

Page 6: Lecture 22

User Defined Exception

User Defined Exception - Example The Example InsufficientFundsException class is a user-

defined exception that extends the Exception class, making it a checked exception.

An exception class is like any other class, containing useful fields and methods.

Example is taken from the following linkhttp://www.tutorialspoint.com/java/java_exceptions.htm

6

Page 7: Lecture 22

User Defined Exception

User Defined Exception – Example// File Name InsufficientFundsException.import java.io.*; public class InsufficientFundsException extends Exception {

private double amount; public InsufficientFundsException(double amount) {

this.amount = amount; } public double getAmount() {

return amount; }

}

InsufficientFundsException is user defined exception class

7

Page 8: Lecture 22

User Defined Exception

User Defined Exception - Example

To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

Example is taken from the following linkhttp://www.tutorialspoint.com/java/java_exceptions.htm

8

Page 9: Lecture 22

User Defined Exception

import java.io.*;

public class CheckingAccount {

private double balance;

private int number;

public CheckingAccount(int number) {

this.number = number;

}

public void deposit(double amount) {

balance += amount;

}

9

Page 10: Lecture 22

User Defined Exception

public void withdraw(double amount) throws

InsufficientFundsException {

if(amount <= balance) {

balance -= amount;

}

else {

double needs = amount - balance;

throw new InsufficientFundsException(needs);

}

}

10

Page 11: Lecture 22

User Defined Exception

public double getBalance() {

return balance;

}

public int getNumber() {

return number;

}

}

11

Page 12: Lecture 22

User Defined Exception

public class BankDemo {

public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500...");

c.deposit(500.00);

try {

System.out.println("\nWithdrawing $100...");

c.withdraw(100.00);

System.out.println("\nWithdrawing $600...");

c.withdraw(600.00);

}

catch(InsufficientFundsException e) {

System.out.println("Sorry, but you are short $" +

e.getAmount()); e.printStackTrace(); } } }12

Page 13: Lecture 22

assert Statement

13

What is an assert Statement? An assertion is a statement in Java that enables you to

test your assumptions about your program. Each assertion contains a boolean expression that you

believe will be true when the assertion executes. By verifying that the boolean expression is indeed true,

the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

Page 14: Lecture 22

assert Statement

14

Why use assertions? Programming by contract

Pre-conditions

– Assert precondition as requirement of client

Post-conditions

– Assert post-condition as effect of client method

Page 15: Lecture 22

assert Statement

15

Simple Assertion Form The assertion statement has two forms The first is:

assert Expression1 ; Where Expression1 is a boolean expression When the system runs the assertion, it evaluates

Expression1 and if it is false throws an AssertionError with no details

Page 16: Lecture 22

assert Statement

16

Complex Assertion Form The second form of the assertion statement is:

assert Expression1 : Expression2 ; where: – Expression1 is a boolean expression– Expression2 is an expression that has a

value – It cannot invoke of a method that is

declared void

Page 17: Lecture 22

assert Statement

17

Complex Assertion Form Use the second version of the assert statement to

provide a detailed message for the AssertionError The system passes the value of Expression2 to the

appropriate AssertionError constructor, which uses the string error message

The purpose of the message is to communicate the reason for the assertion failure

Don’t use assertions to flag user errors—why not?

Page 18: Lecture 22

assert Statement

18

When an Assertion Fails Assertion failures are labeled in stack trace with the file

and line number from which they were thrown Second form of the assertion statement should be used

in preference to the first when the program has some additional information that might help diagnose the failure

Page 19: Lecture 22

assert Statement

19

Simple Exampleimport java.util.Scanner;  class AssertionExample{   public static void main( String args[] ){      Scanner scanner = new Scanner( System.in );    System.out.print("Enter ur age ");        int value = scanner.nextInt();    assert value>=18:" Not valid";      System.out.println("value is "+value);   }   }  

http://www.javatpoint.com/assertion-in-java

Page 20: Lecture 22

assert Statement

20

Compiling and Running If you use assertion, It will not run simply because assertion is

disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used.

Compile it by: javac AssertionExample.java Run it by: java -ea AssertionExample

Page 21: Lecture 22

21