| SN | Methods with Description |
|---|---|
| 1 | public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. |
| 2 | public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. |
| 3 | public String toString() Returns the name of the class concatenated with the result of getMessage() |
| 4 | public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. |
| 5 | public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. |
| 6 | public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. |
Friday, 13 January 2012
Exceptions Methods
Effective Java Exception handling
2. The best use of exceptions is to translate exception in the calling method to the exception which is more appropriate for it and you should let the cause of the exception flow from the called methods to the calling methods.
For this you should have one of the constructors of your Exception classes like
1: // Exception with chaining-aware constructor
2: class HigherLevelException extends Exception {
3: HigherLevelException(Throwable cause) { 4: super(cause); 5: } 6: }3. Don’t use the 2nd point too much if the lower level method can get away with the exception, then you should do that. Don’t overload the calling methods too much to handle the exceptions thrown by the lower methods.
4. If you are declaring your own exception class you can always include some methods or attributes which can be used to convey more about the exception when it occurs.
5. Try to reuse exceptions (comes generally when you are creating your own API). The most reusabel exceptions are
IllegalArgumentException, IllegalStateException, NullPointerException, IndexArrayOutOfBounds and some more.
6. Most importantly, use Exceptions only for Exceptional conditions. Don’t write your logic which is based on exceptions. For example, don’t do like this
1: // wrong usage of exception handling
2: try {
3: someObject.someMethod();4: } catch (NullPointerException npe)
5: {6: // other code
7: }8. All of the unchecked throwables you implement should subclass RuntimeException (directly or indirectly).
9. Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract established by the API specification. For example, the contract for array access specifies that the array index must be between zero and the array length minus one. ArrayIndexOutOfBoundsException indicates that this precondition was violated.
10. Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag. Don’t take the shortcut of declaring that a method throws some superclass of multiple exception classes that it can throw. As an extreme example, never declare that a method “throws Exception” or, worse yet, “throws Throwable.”
11.Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration. It is important that the programmers using your API be aware of which exceptions are checked and which are unchecked, as their responsibilities differ in these two cases. The documentation generated by the Javadoc @throws tag in the absence of the method header generated by the throws declaration provides a strong visual clue to help the programmer distinguish checked exceptions from unchecked.
12. If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment rather than documenting it individually for each method. A common example is NullPointerException. It is fine for a class’s documentation comment to say, “All methods in this class throw a NullPointerException if a null object reference is passed in any parameter,” or words to that effect.
13. To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception. You must write the toString() method of your exception carefully.
14. Failure Atomicity(Object remains in consistence state after a failure)-
ways to achieve failure atomicity:
a. A closely related approach to achieving failure atomicity is to order the computation so that any part that may fail takes place before any part that modifies the object.
b. This approach is a natural extension of the previous one when arguments cannot be checked without performing a part of the computation.
c. A third and far less common approach to achieving failure atomicity is to write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began. This approach is used mainly for durable (disk-based) data structures.
d.A final approach to achieving failure atomicity is to perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete. This approach occurs naturally when the computation can be performed more quickly once the data has been stored in a temporary data structure. For example, Collections.sort dumps its
input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.
As a rule, any generated exception that is part of a method’s specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.
15. An empty catch block defeats the purpose of exceptions, which is to force you to handle exceptional conditions. At the very
least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
Monday, 26 December 2011
Extend Thread vs implement Runnable
There are two ways to create your own thread type: subclass java.lang.Thread class, or implementing java.lang.Runnable and pass it to Thread constructor or java.util.concurrent.ThreadFactory. What is the difference, and which one is better?
1, The practical reason is, a Java class can have only one superclass. So if your thread class extends java.lang.Thread, it cannot inherit from any other classes. This limits how you can reuse your application logic.
2, From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a Runnalbe impl, and the latter is job of the Thread class.
3, A Runnable instance can be passed to other libraries that accept task submission, e.g., java.util.concurrent.Executors. A Thread subclass inherits all the overhead of thread management and is hard to reuse.
4, Their instances also have different lifecycle. Once a thread is started and completed its work, it's subject to garbage collection. An instance of Runnalbe task can be resubmitted or retried multiple times, though usually new tasks are instantiated for each submission to ease state management.
Thursday, 22 December 2011
One java - 2 compilers (Javac and JIT)
It seems like that for students there is a lot of confusion regarding how Java/The JVM works because there are TWO compilers involve, so when someone mentions a compiler or the Just In Time compiler some of them would imagine it’s the same one, the Java Compiler..
So how does it really works?
It’s simple..
1) You write Java code (file.java) which compiles to “bytecode“, this is done using the ‘javac” the 1st compiler.
It’s well known fact that Java can be written once get compiled and run anywhere (on any platform) which mean that different types of JVM can get installed over any type of platform and read the same good old byte code
2) Upon execution of a Java program (the class file or Jar file that consists of some classes and other resources) the JVM should somehow execute the program and somehow translate it to the specific platform machine code.
In the first versions of Java, the JVM was a “stupid” interprater that executes byte-code line by line….that was extremely slow…people got mad, there were a lot of “lame-java, awesome c” talks…and the JVM guys got irratated and reinvented the JVM.
the “new” JVM initially was available as an add-on for Java 1.2 later it became the default Sun JVM (1.3+).
So what did they do? they added a second compiler.. Just In Time compiler(aka JIT)..
Instead of interpreting line by line, the JIT compiler compiles the byte-code to machine-code right after the execution..
Moreover, the JVM is getting smarter upon every release, it “knows” when it should interpat the code line-by-line and what parts of the code should get compiled beforehand (still on runtime).
It does that by taking real-usage statistics, and a long-list of super-awesome heuristics..
The JVM can get configured by the user in order to disable/enable some of those heuristics..
To summarize, In order to execute java code, you use two different compilers, the first one(javac) is generic and compiles java to bytecode, the second(jit) is platform-dependent and compiles some portions of the bytecode to machine-code in runtime!
Optimizing and Speeding up the code in Java
Finalizers: object that overwrites the finalize() method (“Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.”) is slower!(for both allocation and collection) if it’s not a must, do clean ups in other ways ( e.g. in JDBC close the connection using the try-catch-finally block instead)
New is expensive: creating new heavy object() on the heap is expensive!, it’s recommended to recycle old objects (by changing their fields) or use the flyweight design pattern.
Strings : (1) Strings are immutable which mean that upon usage of the + operator between 2 strings the JVM will generate a new String(s1+s2) on the heap (expensive as I just mentioned), in order to avoid that, it’s recommended to use the StringBuffer.(Update) since JDK 1.5 was introduced StringBuilder is a better option than Stringbuffer in a single-threaded environment.
(2) Don’t convert your strings to lower case in order to compare them, use String.equalIgnoreCase() instead.
(3) String.startswith() is more expensive than String.charat(0) for the first character.
Inline method: inline is a compiler feature, when you call a method from anywhere in your code, the compiler copies the content of the inline method and replace the line that calls the method with it.
Obviously,It saves runtime time: (1) there is no need to call a method (2) no dynamic dispatch.
In some languages you can annotate a method to be inline, yet in Java it’s impossible, it’s the compiler decision.
the compiler will consider inline a method if the method is private.
My recommendation is to search in your code for methods that are heavily used(mostly in loops) and annotate those method as private if possible.
Don’t invent the wheel: the java api is smart and sophisticated and in some cases use native implementation, code that you probably can’t compete with. unless you know what you are doing (performance wise) don’t rewrite methods that already exists in the java API. e.g. benchmarks showed that coping and array using a for loop is at least n/4 times slower than using System.arraycopy()
Reflection: reflection became much faster for those of you who use the most recent JVMs, yet using reflection is most certainly slower than not using it. which mean that you better avoid reflection if there is no need.
Synchronization: Some data structures auto-support concurrency, in case of a single thread application don’t use those to avoid overhead e.g. use ArrayList instead of a Vector
Multithreads: in case of a multi processor use threads, it will defiantly speed up your code, if you are not a thread expert some compilers know how to restructure your code to thread automatically for you. you can always read a java threads tutorial as well
Get familiar with the standard data structures: e.g. if you need a dast for puting and retriving objects use HashMap and not an ArrayList. (O(1))
Add an id field, for faster equals(): object that contains many fields are hard to compare ( equals() wise), to avoid that add an id(unique) field to your object and overwrite the equals() method to compare ids only.
Be careful, In case your code already works, optimizing it is a sure way to create new bugs and make your code less maintainable!
it’s highly recommended to time your method before and after an optimization.


