Nothing Special   »   [go: up one dir, main page]

Trigonometric Identities

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

The finally Block The finally block always executes when the try block exits.

This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try orcatch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeListmethod. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.

1. The new FileWriter statement fails and throws an IOException. 2. The vector.elementAt(i) statement fails and throws
an ArrayIndexOutOfBoundsException.

3. Everything succeeds and the try block exits normally.


The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. The following finally block for the writeList method cleans up and then closes the PrintWriter. finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } In the writeList example, you could provide for cleanup without the intervention of a finally block. For example, you could put the code to close the PrintWriter at the end of the try block and again within the exception handler for ArrayIndexOutOfBoundsException, as follows. try { // Don't do this; // it duplicates code. out.close(); } catch (FileNotFoundException e) { // Don't do this; // it duplicates code. out.close(); System.err.println("Caught: " + "FileNotFoundException: " +

e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { System.err.println("Caught " + " IOException: " + e.getMessage()); } However, this duplicates code, thus making the code difficult to read and error-prone should you modify it later. For example, if you add code that can throw a new type of exception to the try block, you have to remember to close the PrintWriter within the new exception handler.

Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finallyblock to ensure that resource is always recovered. If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. The next section has more information.

Exception in Java

Exception are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language. Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions. However Java provides mechanisms to handle such situations through its superb exception handling mechanism. The Java programming language uses Exception classes to handle such erroneous conditions and exceptional events. Exception Object In java, when any kind of abnormal conditions occurs with in a method then the exceptions are thrown in form of Exception Object i.e. the normal program control flow is stopped and an exception object is created to handle that exceptional condition. The method creates an object and hands it over to the runtime system. Basically, all the information about the error or any unusual condition is stored in this type of object in the form of a stack. This object created is called an exception object the process is termed

as throwing an exception. The mechanism of handling an exception is called catching an exception or handling an Exception or simply Exception handling.

As we have known that after throwing an exception it is handed off to the runtime system that finds a possible method from an ordered list of methods to handle it. The list of this type of methods is known as the call stack As we have already learned that, what are the exceptions. Point to be remember here is that exceptions are not errors rather they are some abnormal conditions that aren't necessarily errors. Therefore, the process of detecting the exceptions and responding to them as well is known as Exception handling. Following are the advantages of Exception-handling in Java: Exception provides the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. One of the significance of this mechanism is that it throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.

With the help of this mechanism the working code and the error-handling code can be disintegrated. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks.

Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the lower level in the chain can be handled by the methods higher up the call chain .

Sample Code The basic syntax to handle an Exception looks like this: String myException() { try { return myMethod(); } catch ( IOException e ) { return null; } }

There are three types of Exceptions:

1. Checked Exceptions - These are the exceptions which occur during the compile time of the
program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptions extend thejava.lang.Exception class These exceptional conditions should be anticipated and recovered by an application. Furthermore Checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses. For example if you call the readLine() method on a BufferedReader object then theIOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throwsjava.io.FileNotFoundException which abrupt the application to succeed. Hence this exception will be caught by a well-written application and will also prompt to correct the file name.

Here is the list of checked exceptions.

NoSuchFieldException

InstantiationException IllegalAccessException ClassNotFoundException

NoSuchMethodException CloneNotSupportedExcepti on InterruptedException

2. Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the
runtime of the program. Unchecked exceptions are internal to the application and extend thejava.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.

Lets take the same file name example as described earlier. In that example the file name is passed to the constructor for FileReader. However, the constructor will throwNullPointerException if a logic error causes a null to be passed to the constructor. Well in this case the exception could be caught by the application but it would rather try to eliminate the bug due to which the exception has occurred. You must have encountered the most common exception in your program i.e. the ArithmeticException. I am sure you must be familiar with the reason of its occurrence that is when something tries to divide by zero. Similarly when an instance data member or method of a reference variable is to be accessed that hasn't yet referenced an object throws NullPointerException.

Here is the list of unchecked exceptions.

IndexOutOfBoundsExce ption

ArrayIndexOutOfBoundsE xception ClassCastException ArithmeticException NullPointerException IllegalStateException SecurityException


3.

4. Error - The errors in java are external to the application. These are the exceptional conditions
that could not be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement. Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown. This error will cause the program to terminate but if an application wants then the error might be caught. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Hence we conclude that Errors and runtime exceptions are together called as unchecked

Exception Classes

The hierarchy of exception classes commence from Throwable class which is the base class for an entire family of exception classes, declared in java.langpackage as java.lang.Throwable. A throwable contains a snapshot of the execution stack at the time it was created and also a message string that gives more information about the error. This class can be instantiated and thrown by the program. The throwable class is further divided into two subclasses :-

1. Exceptions - Exceptions are thrown if any kind of unusual condition occurs that can be caught.
Sometimes it also happens that the exception could not be caught and the program may get terminated. Remember that they are a member of Exception family and can be type ofChecked or Unchecked exception.

2. Errors - When any kind of serious problem occurs which could not be handled easily
likeOutOfMemoryError then an error is thrown. Well, errors are not something which is thrown by you rather they are thrown by the Java API or by the Java virtual machine itself i.e. only the exceptions are thrown by your code and not the errors. Also Remember that they are a member of Error family. The exception classes can be explained as well seeing the exception hierarchy structure:

The java.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked. EXCEPTIONS DESCRIPTION Arithmetic errors such as a divide by zero Arrays index is not within array.length Related Class not found CHECKED UNCHECKED

ArithmeticException

YES

ArrayIndexOutOfBoundsException

YES

ClassNotFoundException IOException

YES

InputOuput field not found YES Illegal argument when calling a method One thread has been

IllegalArgumentException

YES

InterruptedException

interrupted by another thread

YES

NoSuchMethodException NullPointerException

Nonexistent method Invalid use of null

YES -

YES

reference Invalid string for conversion to number

NumberFormatException

YES

As you have come to know that exceptions are Objects that means an object is thrown when you throw an exception. Moreover only those objects could be thrown whose classes are derived fromThrowable. It is interesting to note here that the objects of your own design could also be thrown provided that they should be the subclass of some member of the Throwable family. Also the throwable classes which are defined by you must extend Exception class. It depends upon the situation that whether to use an existing exception class from java.lang or create any of your own. Such as IllegalArgumentException, a subclass of RuntimeException in java.lang can be thrown if any method with an invalid argument is thrown by you. On the other hand you need not to worry if you wish to impart some more information about any unusual condition other than a class from java.lang because it will be indicated by the class of exception object itself. For example, if a thrown exception object has class IllegalArgumentException, that indicates someone passed an illegal argument to a method. Sometimes you will want to indicate that a method encountered an abnormal condition that isn't represented by a class in the Throwable family of java.lang. For instance, lets tweak an example below that demonstrates the exceptional conditions that might occur while driving a car. // In Source Packet in file except/ex1/SpeedException.java class SpeedException extends Exception { } // In Source Packet in file except/ex1/VeryFastException.java class VeryFastException extends SpeedException { } // In Source Packet in file except/ex1/VerySlowException.java class VerySlowException extends SpeedException { }

Lets tweak the diagram below.

It is clear from the above program that there is something abnormal with the speed of the car i.e. either it is very fast or it is very slow. Hence two exceptions are thrown by the program - VeryFastExceptionand VerySlowException. To be more precise the SpeedException family specifies three new exceptions thrown by the program which indicate some abnormal conditions. That is the SpeedException specifies that there is something unusual with the speed; VeryFastException and VerySlowException specifies the abnormal conditions of the speed.

Reciprocal Identities

For angle at which the functions are defined:

Quotient Identities
The definitions of the trig functions led us to the reciprocal identities above. They also lead us to another set of identities, the quotient identities. Consider first the sine, cosine, and tangent functions. For angles of rotation (not necessarily in the unit circle) these functions are defined as follows:

Given these definitions, we can show that

, as long as

The equation is therefore an identity that we can use to find the value of the tangent function, given the value of the sine and cosine.

Example 3: If Solution:

and

, what is the value of

Example 4: Show that Solution: This is also an identity that you can use to find the value of the cotangent function, given values of sine and cosine. Both of the quotient identities will also be useful in chapter 3, in which you will prove other identities.

Pythagorean Identities
For angle at which the functions are defined:

(1) cos2 + sin2 = 1 (2) 1 + tan2 = sec2 (3) 1 + cot2 = csc2


Dividing both sides of the first equation by cos2 results in the second equation. Similarly, dividing both sides of the first equation by sin2 results in the third equation.

You might also like