• No results found

exception.ppt

N/A
N/A
Protected

Academic year: 2020

Share "exception.ppt"

Copied!
30
0
0

Loading.... (view fulltext now)

Full text

(1)

Exceptions Handling : Exception , Handling of Exception, Using try-catch ,

Catching Multiple Exceptions , Using finally clause , Types of Exceptions, Throwing Exceptions,

(2)

Exception

 Exceptions are a mechanism used by many

programming languages to describe what to do when something unreported happens.

 Something unreported is an error of some type.  Like:

When a method is invoked with unacceptable arguments – When a network connection fails

(3)

Exception

 Exceptions handle unexpected situations –

Illegal argument, network failure, or file not found

(4)

 Conditions that can readily occur in a correct program

are checked exceptions.

 These are represented by the Exception class.

 Severe problems that normally are treated as fatal or

situations that probably reflect program bugs are unchecked exceptions.

 Fatal situations are represented by the Error class.  Probable bugs are represented by the

RuntimeException class.

 The API documentation shows checked exceptions

(5)

Exception Example

1 public class AddArguments {

2 public static void main(String args[]) { 3 int sum = 0;

4 for ( String arg : args ) {

5 sum += Integer.parseInt(arg); 6 }

7 System.out.println("Sum = " + sum); 8 }

(6)

Exception Example

java AddArguments 1 2 3 4  Sum = 10

java AddArguments 1 two 3.0 4

 Exception in thread "main" java.lang.NumberFormatException:

For input string: "two"

 at

java.lang.NumberFormatException.forInputString(NumberForm atException.java:48)

 at java.lang.Integer.parseInt(Integer.java:447)  at java.lang.Integer.parseInt(Integer.java:497)  at AddArguments.main(AddArguments.java:5)

(7)

The try-catch Statement

1 public class AddArguments2 {

2 public static void main(String args[]) { 3 try {

4 int sum = 0;

5 for ( String arg : args ) {

6 sum += Integer.parseInt(arg); 7 }

8 System.out.println("Sum = " + sum);

9 } catch (NumberFormatException nfe) {

10 System.err.println("One of the command-line " 11 + "arguments is not an integer.");

12 }

(8)

The try-catch Statement

java AddArguments2 1 two 3.0 4

 One of the command-line arguments is not

(9)

The try-catch Statement

1 public class AddArguments3 {

2 public static void main(String args[]) { 3 int sum = 0;

4 for ( String arg : args ) {

5 try {

6 sum += Integer.parseInt(arg);

7 } catch (NumberFormatException nfe) {

8 System.err.println("[" + arg + "] is not an integer" 9 + " and will not be included in the sum.");

10 }

11 }

12 System.out.println("Sum = " + sum); 13 }

(10)

java AddArguments3 1 two 3.0 4  [two] is not an integer and will not be

included in the sum.

 [3.0] is not an integer and will not be included

in the sum.

(11)

The try-catch Statement

A try-catch statement can use multiple catch clauses: try {

// code that might throw one or more exceptions Try{}

Catch(){}

} catch (MyException e1) {

// code to execute if a MyException exception is thrown } catch (MyOtherException e2) {

// code to execute if a MyOtherException exception is thrown } catch (Exception e3) {

// code to execute if any other exception is thrown }

(12)

The finally Clause

The finally clause defines a block of code that always

executes. try {

startFaucet(); waterLawn(); }

catch (BrokenPipeException e) { logProblem(e);

}

finally {

stopFaucet(); }

(13)
(14)

Common Exceptions

 FileNotFoundException  NumberFormatException  ArithmeticException

(15)

The Handle or Declare Rule

Use the handle or declare rule as follows:

• Handle the exception by using the try-catch-finally block. • Declare that the code causes an exception by using the throws clause.

void trouble() throws IOException { ... }

void trouble() throws IOException, MyException { ... } Other Principles

• You do not need to declare runtime exceptions or errors. • You can choose to handle runtime exceptions.

(16)

Writing Exception Subclasses

class OwnCreated extends Exception {

public OwnCreated(String message) {

super(message); }

(17)

class Bank {

int balance;

void SetBalance(int bal) {

balance=bal; }

void withdraw(int bal) throws OwnCreated { boolean check=true; if((balance-bal)>0) { check=true; } else

{ check=false; } if(!check) {

(18)

Creating Your Own Exceptions

public class OwnException {

public static void main(String[] args) throws OwnCreated, IOException{

Bank b1=new Bank(); b1.SetBalance(5000);

b1.withdraw(6000); }

(19)

run:

Exception in thread "main" OwnCreated: Please try again Available balance is low: 5000

at Bank.withdraw(OwnException.java:37)

at OwnException.main(OwnException.java:51) Java Result: 1

(20)

throw

 It is possible for your program to throw an

exception explicitly, using the throw statement.

 The general form of throw is shown here:

(21)

 Here, ThrowableInstance must be an object

of type Throwable or a subclass of Throwable.

 Simple types, such as int or char, as well as

non-Throwable classes, such as String and Object, cannot be used as exceptions.

(22)

 There are two ways you can obtain a

Throwable object:

– using a parameter into a catch clause, – creating one with the new operator.

(23)

throw

 The flow of execution stops immediately after

the throw statement; any subsequent statements are not executed.

(24)

throw

 The nearest enclosing try block is inspected

to see if it has a catch statement that matches the type of the exception.

(25)

throw

 If it does find a match, control is transferred

to that statement.

 If not, then the next enclosing try statement

is inspected, and so on.

 If no matching catch is found, then the

default exception handler halts the program and prints the stack trace.

(26)

throws

 If a method is capable of causing an

exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.

(27)

throws

 You do this by including a throws clause in the method's

declaration.

 A throws clause lists the types of exceptions that a

method might throw.

 This is necessary for all exceptions, except those of type

Error or RuntimeException, or any of their subclasses.

 All other exceptions that a method can throw must be

declared in the throws clause. If they are not, a compile-time error will result.

(28)

finally

 finally creates a block of code that will be

executed after a try/catch block has

completed and before the code following the try/catch block.

(29)

 The finally block will execute whether or not an

exception is thrown.

 If an exception is thrown, the finally block will execute

even if no catch statement matches the exception.

 Any time a method is about to return to the caller

from inside a try/catch block, via an uncaught

exception or an explicit return statement, the finally clause is also executed just before the method

(30)

 This can be useful for closing file handles

and freeing up any other resources that

might have been allocated at the beginning of a method with the intent of disposing of them before returning.

 The finally clause is optional. However, each

try statement requires at least one catch or a finally clause.

References

Related documents

The book’s first section offers a foundation of four simple but comprehensive Lean key performance indicators (KPIs): waste of the time of things (as in cycle time),

Most of the phases of the Architecture Development Method in TOGAF are executed in a project fashion, with the exception of implementation governance and architecture

Most of the phases of the Architecture Development Method in TOGAF are executed in a project fashion, with the exception of implementation governance and architecture

 A)In case you declare the exception, if exception does not occur, the code will be executed fine.  B)In case you declare the exception if exception occures, an exception will be

Dear Satyanarayana, You can ask upto 3 questions and get reply from our astrologer click here to fill the form and pay... 11/16/2014 Telugu Jathakam | లగ మ ల - Telugu

Concerning divorce itself existed that bible divorce exception clause applies them up a bible forbids this clause does it is not see any cause in order to understand is not for

Debugging – Types of errors - Exceptions-Syntax of exception-Handling code -Multiple catch statements -Exception hierarchy-General catch handler- Using finally statement- Nested try

(The court held in the case (1) That where a check is accepted or certified by the bank on which it is drawn, the bank is estopped to deny the genuineness of the drawer's