JAVA Exception

if a program obtains a resource, the program should return that resource before program termination. aborting a program could leave a resource in a state in which other programs would not be able to acquire the resource; hence, This is called resource leak .

 

 java.lang.Throwable--Exception

                                  |-Error

Error s are particularly serious system problems that generally should not be caught. Exceptions are caused by problems that should be caught and processed during program execution to make a program more robust.

 

all exceptions are objects of classes derived from superclass Exception. If Exceptions are not caught in GUI - based application, the GUI remains displayed and the user can continue using the application even after the default exception handler runs. but the program is in an inconsistent state and may produce incorrect results. a nonGUI - based application will terminate when the default exception hanlder is not caught.

 

try{

//code that may generate exceptions or throw exception

}

catch(Throwable throwable)

{

//catch all exceptions and errors

//statements to process an exception

//followed by one or more catch blocks.

}

catch(Exception e)

{

//catch all exceptions

//statements to process an exception

//followed by one or more catch blocks.

//the order of the handlers will affect the manner in which the exception is handled.

}

catch( IOException e)

{

// will not execute because the Exception catches all possible exceptions before this one.

}

finally{

// optional finally block always executes.

//finally block is the ideal location to release resources acquired in its corresponding try block to prevent resource leaks , since java will only garbage collect an object until there are no more references to the object

//the finally block will execute even if there are return, break or continue statement in try block. then the effect of the return, break or continue statement will occur.

}

 

when a method throws a exception, the program control leaves the try block and continues execution at the first catch block. the program searches the catch block in order looking for an appropriate handler. if the type of the thrown exception matches the parameter type in one of the catch blocks, the code for that catch block executes.

the program skips the exception handlers and resumes execution after the last catch block if no exception is thrown. finally block executes regardless of whether an exception occurs.

 

throws clause specifies the exceptions the method throws. Java uses termination model of exception handling which means the block where exception occurred terminates and the program cannot return directly to the throw point. there is another model called resumption model of exception handling , which control return to the point at which the exception occurred and resume execution.

 

int functionName(parameterList) throws Exception 1,Exception2,Exception3,...,

 

RuntimeException s occur during the execution of the program and can be avoided by coding properly. in the throws clause, Errors and RuntimeException do not need to be listed. If a non-runtimeException is thrown by a method or by a method called by this method throws non-RuntimeException,  each of those exceptions must be declared in the throws clauseof that method OR caught in a try/catch in that method.

 

If a subclass method overrides a superclass method, it is an error for the subclass method to list more exceptions in its throws list than the overriden superclass method does. A subclass's throws list can contain a subset or the same list of the superclass's throws list.

 

public void superMethod() throws Exception1, Exception2, Exception3 //父类

 

public void superMethod() throw Exception1, Exception2,Exception3//子类

 

In case that there is no exception handlers catch the exception, non-GUI application terminates while GUI application carried on but my produce incorrect results.

 

if a catch that catches a superclass object  is placed before a catch for that class's subclass type, it is syntax error , 如下所示

try{

//可能抛异常的code

}

catch(Exception e)
        {
            System.out.println(e.toString());
        }
        catch(NullPointerException e1) //Error: unreachable catch block
        {
            System.out.println(e1.toString());
        }

 

一个 Exception 的例子.

An exception class can contain instance variables and methods. A typical exception class contains only two constructors, one that takes no arguments and one that takes one argument. 例子

 

public class DivideByZeroException extends rithmeticException{

public DividByZeroException()

{

super ("Attempted to divide by zero");

}

public DivideByZeroException(String message)

{

// this message is the descriptive String message of the throwable class. this message can be obtained with method //getMessage.

super (message);

}

}

public double quotient(int numerator, int denominator) throws DivideByZeroException

{

if(denominator == 0)

throws new DividByZeroException();

***************

 

}

 

if the catch handler wants to let some other catch handler handle the exception or may decide it cannot process the exception. the handler can rethrow the exception with the statement

catch(Exception e)

{

throw e ; //it rethrows the exception reference to the next enclosing try block.

}

 

Constructor, subclass and superclass

what happens when an error is detected in a constructor?

In java, the proper mechanism to to throw an exception in the constructor to the code creating the object. The thrown object contains the information about the failed constructor call and the caller is responsible for handling the exceptions.

 

if a catch is writen to catch exception objects of a superclass type, it can also catch all objects of subclasses of that superclass object. catching the superclass guarantees that objects of all subclasses will be caught.

 

If an exception is thrown for which no local catch is available, when control enters the local finaly block, the finaly block could also throw an exception. If this happens, the first exception will be lost. So we need to avoid place code that can throw an exception in a finally block.

 

printStackTrace and getMessage

Exception derive from class Throwable. Class Throwable offers a printStackTrace method that prints the method call stack trace for the object. the getMessage returns the descriptive String stored in an exception.

 

printStackTrace outptus to the standard error stream an error message with the class name of the exception, the descriptive String stored in the exception and a list of the methods that had not completed excution when the exception was thrown.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值