tailieunhanh - Object Oriented Programming using Java phần 10

Có lần khi nó làm cho ý nghĩa đối với một chương trình cố tình ném một ngoại lệ. Đây là trường hợp khi chương trình phát hiện ra một số loại điều kiện đặc biệt hoặc lỗi, nhưng không có cách nào hợp lý để xử lý các lỗi tại điểm nơi mà vấn đề được phát hiện. | nication. The first try statement is there to make sure that we don t even try to communicate over the network unless we have successfully opened a connection. The pseudocode in this example follows a general pattern that can be used to robustly obtain a resource use the resource and then release the resource. Throwing Exceptions There are times when it makes sense for a program to deliberately throw an exception. This is the case when the program discovers some sort of exceptional or error condition but there is no reasonable way to handle the error at the point where the problem is discovered. The program can throw an exception in the hope that some other part of the program will catch and handle the exception. This can be done with a throw statement. In this section we cover the throw statement more fully. The syntax of the throw statement is throw exception-object The exception-object must be an object belonging to one of the subclasses of Throwable. Usually it will in fact belong to one of the subclasses of Exception. In most cases it will be a newly constructed object created with the new operator. For example throw new ArithmeticException Division by zero The parameter in the constructor becomes the error message in the exception object if e refers to the object the error message can be retrieved by calling . You might find this example a bit odd because you might expect the system itself to throw an ArithmeticException when an attempt is made to divide by zero. So why should a programmer bother to throw the exception Recalls that if the numbers that are being divided are of type int then division by zero will indeed throw an ArithmeticException. However no arithmetic operations with floating-point numbers will ever produce an exception. Instead the special value is used to represent the result of an illegal operation. In some situations you might prefer to throw an ArithmeticException when a real number is divided by zero. An .

TỪ KHÓA LIÊN QUAN