• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Exceptions (long one) Your response requested.

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I reviewed the Sun requirements for java exceptions and came up with my notes for study. Please look at them and let me know what I got wrong and what I left out. Please let me know if some things that are not clear enough. Others can answer your questions too. There are 10 exceptions in my notes at the end which I have not defined yet, but I will.

THE REQUIREMENTS FROM SUN WEBSITE

Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.

Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.

Recognize situations that will result in any of the following being thrown:

ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.


MY STUDY NOTES

I. Exception Hierarchy: all exception classes inherit from Throwable. Error and Exception descend from Throwable and from Exception the classes Runtime and IOException descend. Error exceptions are internal runtime system errors and beyond a programmers scope. They should not be thrown. Runtime exceptions represent coding errors that should be corrected within the code. It is not good programming practice to catch these. IOExceptions that may occur in a method should normally be caught and handled within the method. These are called checked exceptions.

Runtime exceptions: bad cast, array access out of bounds, null pointer access ...
IOExceptions: file not found, reading past EOF, open malformed URL �

Checked exceptions require you to provide code to handle them. The compiler checks to see if you handle checked exceptions. Either catch or declare (throw) them.

II. To declare:
public FName(String name) throws FileNotFoundException

to declare than one:
public FName(String name) throws FileNotFoundException, MalformedURLException

III. To throw:
throw new EOFException();
or
EOFExcption e = new EOFException();
throw e;
or
throw new EOFException(gripetext);


IV. To catch and handle:

try
{ �
}
catch( ExceptionType e)
{ �
}
finally
{ �
}

Code goes in try block. Handler code goes in catch block. Always code into finally block.

when to declare:
1. your method may throw a checked exception 2. you call a method that says it throws exception. 2) you throw a checked exception but do not handle it.

V. Exception Processing.

When an exception is thrown, the runtime system checks for a matching catch block. The catch block is executed and then the finally block is executed. Execution then continues after the end of the try block.

If no matching catch block is found the finally block is executed and then control passes back to the calling method which checks for a matching catch block.

If no try block is specified then control passes back to the calling method which searches for a catch block.

When over riding a method you cannot throw new or more general exceptions than in overridden method.

Useful methods:
e.getMessage();
e.getClass.getName();
e. initCause();
e. printStackTrace();

VI. Specific Exceptions.

ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError
 
Joe Wolfe
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ArrayIndexOutOfBoundsException: Runtime Exception: Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

ClassCastException: Runtime Exception: Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

IllegalArgumentException: Runtime Exception: Thrown to indicate that a method has been passed an illegal or inappropriate argument.

IllegalStateException: Runtime Exception: Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

NullPointerException:
Runtime Exception: Thrown when an application attempts to use null in a case where an object is required.

NumberFormatException: Runtime Exception: Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

AssertionError: Error : Thrown to indicate that an assertion has failed.

ExceptionInInitializerError: Error: Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

StackOverflowError: Error: Thrown when a stack overflow occurs because an application recurses too deeply.

NoClassDefFoundError: Error: Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's an Exceptions question I just made up. It addresses a situation that's frequently asked about in these forums. (The answer is covered in the bullet points I'm posting below, so you might want to try answering the question before looking at the next post.)

What will be the result of attempting to compile and run the following code?

a) Will not compile because there is no catch block.
b) Will not compile because the uncaught Exception is not declared.
c) Compiles and prints "abc".
d) Compiles and prints "OK here".
e) Compiles and prints "abc OK here".
 
marc weber
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I like your approach for preparing!

You might want to add the following to your notes:
  • Checked exceptions include java.lang.Exception and all its subclasses other than RuntimeExceptions. (I think this was unclear in your notes, which seems to suggest that all checked exceptions are derived from IOException.)
  • A try block requires either a catch block or finally block. For each try block, there can be multiple catch blocks, but no more than one finally block.
  • If there are multiple catch blocks, they should be ordered from most-specific to least-specific, since the first matching catch block will be used.
  • Constructors are not inherited, so (unlike methods) they can throw Exceptions that are not declared in base class constructors. However, since derived constructors call base constructors, the derived constructors must still declare any base Exceptions.
  • A return statement in the finally block will cause any caught exception to be "lost," since the method will return normally.
  •  
    Ranch Hand
    Posts: 206
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks Marc,

    Last point in your notes was totally new to me. Good knowledge sharing....

    I will be very greatful if I could get such points from you all for topics Generics and regex, my weakest areas...Can I start a new thread for it?

    Also want to add one more point to these exception notes:

    -> The exception thrown last by the method will override all the previous exceptions.

    EG


    The above code will throw only ClassCastException as it was thrown last.

    Thanks,
    Megha
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by megha joshi:
    Thanks Marc,

    Last point in your notes was totally new to me...


    Actually it needs a minor change (in italics):

    A return statement in the finally block will cause any thrown Exception to be "lost," since the method will return normally.
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by megha joshi:
    ...Also want to add one more point to these exception notes:

    -> The exception thrown last by the method will override all the previous exceptions...


    Small detail on this point: Since the word "override" has special meaning, I think I would change it to something like "replace" or "supercede."
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by megha joshi:
    ...I will be very greatful if I could get such points from you all for topics Generics and regex, my weakest areas...Can I start a new thread for it? ...


    Yes, to keep these threads manageable, please start new topics for these points.
    [ May 08, 2007: Message edited by: marc weber ]
     
    Joe Wolfe
    Ranch Hand
    Posts: 87
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks Marc:

    I was confused about the checked exceptions and the ioexceptions. From the text I read it seemed that the only checked exceptions were ioexceptions which struck me as odd. I must look up the other classes to see whats there.

    I notice the error class exceptions are called somethingsomethingerror and the runtime exceptions class are called somethingsomethingexception. This is a good clue to what I am dealing with.

    Well off to check on these other classes of exceptions.

    I will incorporate your comments and corrections into my notes. thanks.

    I understand there is also a chaining of exceptions so that each exception will point to the previous exception so that if three exceptions are thrown then there is a chain we can look up to see what happened.

    I knew about the most specific exceptions first.

    I wonder if you get a compile error if you leave out the catch and finally or it just assumes you knew what you are doing. I'll give it a try.

    Thanks again. Joe.
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Joe Wolfe:
    ...I was confused about the checked exceptions and the ioexceptions. From the text I read it seemed that the only checked exceptions were ioexceptions which struck me as odd. I must look up the other classes to see whats there.

    I notice the error class exceptions are called somethingsomethingerror and the runtime exceptions class are called somethingsomethingexception. This is a good clue to what I am dealing with...


    All Errors are unchecked. All Exceptions are checked unless they are RuntimeExceptions (that is, a RuntimeException or any of its subclasses). Class names usually allow you to distinguish Errors from Exceptions, but you can't rely on names to tell you whether an Exception is a RuntimeException or not.

    A good idea is to check the API documentation for RuntimeException, and look at the list of direct known subclasses. There are really only a few that you should recognize at this point: ArithmeticException, ClassCastException, ConcurrentModificationException, IndexOutOfBoundsException, NegativeArraySizeException, and NullPointerException. Notice that the names pretty much describe problems that might occur at runtime.

    This is why books often single out IOException as a checked exception. From the name, you might mistake it for a RuntimeException. But IOException does not extend RuntimeException, so it is checked.
     
    Ranch Hand
    Posts: 111
    Netbeans IDE Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Hi Mark,

    A return statement in the finally block will cause any caught exception to be "lost," since the method will return normally.



    can you explain this a bit more.

    Regards,

    Abdul Mohsin
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Abdul Mohsin:
    ...can you explain this a bit more...


    An Exception basically says, "There's a problem that prevents me from executing this code." So inside a method, this means, "I'm not going to be able to finish this method and return normally."

    When an exception is thrown, the flow of execution is transferred to the try/catch/finally blocks. However, if the finally block includes a return statement, then the method will return normally and control will be passed to the point at which the method was called. So whatever was caught will basically be lost.

    Note that this is probably a misuse of finally, because if an exception is thrown, do you really want your method to return in all cases? The finally statement is basically for cleanup that should be performed even if the method does not return normally.

    See "What's finally for?" from Thinking in Java, and also the section beneath that, "Pitfall: the lost exception."
     
    Joe Wolfe
    Ranch Hand
    Posts: 87
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Code printed abc okay here.

    so the return causes the exception to be lost.

    also when I complied a try without either catch or finally I got a compile error.

    There were over 80 classes under exception and not runtime. And many of these had subclasses too.
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Joe Wolfe:
    ...also when I complied a try without either catch or finally I got a compile error.

    There were over 80 classes under exception and not runtime. And many of these had subclasses too.


    Yes, a try block requires either a catch or a finally block. If both are missing, the file will not compile.

    I would just assume that Exceptions are checked unless you recognize it as a RuntimeException (and there are only a handful of these you need to be familiar with -- see above).
     
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    hi Marc,
    you wrote:
    Constructors are not inherited, so (unlike methods) they can throw Exceptions that are not declared in base class constructors. However, since derived constructors call base constructors, the derived constructors must still declare any base Exceptions.

    Can you provide an example and explain.
    I am not so clear about this point.
     
    marc weber
    Sheriff
    Posts: 11343
    Mac Safari Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by debasmita pattnayak:
    ...Can you provide an example and explain...


    First, consider a method. If a method is declared to throw an exception, then an overridding method can also throw that type of exception (or a subtype of that exception), but it cannot throw any other type of checked exception.

    Constructors are a bit different. They are not inherited, so they cannot be overridden. Therefore, constructors in derived classes are free to throw any type of Exception, regardless of what might be declared for the superclass constructors.

    However, when a constructor is called, a superclass constructor is always called (either explicitly or implicitly). So if a superclass constructor is declared to throw an exception, then calling a derived class constructor might result in that exception, so the derived constructor must also declare that exception -- even if it has no additional code that might throw anything.

    (Note: A constructor might explicitly call this instead of super, but eventually one of the overloaded constructors must call super.)
     
    Ranch Hand
    Posts: 1710
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks Marc for such a beautiful description of constructors and
    exceptions.



    It is quite helpful.

    Thanks,
     
    megha joshi
    Ranch Hand
    Posts: 206
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I would like to add something that I just cleared my concept about...

    If any one thread throws uncaught exception the JVM doesnt exit, all other threads continue normally and do their functionality. This is also true in the case of main thread throwing an exception...ie. all othe threads continue normally even after main thread throws some uncaught exception.

    Apart from Exceptions ,this also holds true for throwing Throwable or Error instances...

    Thanks,
    Megha
    [ May 13, 2007: Message edited by: megha joshi ]
     
    Ranch Hand
    Posts: 652
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Hi Megha,
    Can you give me a example and explain i am not clear about the points what you mentioned.
     
    debasmita pattnayak
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    hi Megha,
    even i am not clear about the point you mentioned.
    kindly give us an example so that its clear to us.
    thanks
     
    megha joshi
    Ranch Hand
    Posts: 206
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Please find the example below



    class MyThread extends Thread{
    public void run(){
    System.out.println("In MyThread");
    throw new RuntimeException();
    }
    }
    class Test{
    public static void main(String[] args){
    MyThread t = new MyThread();
    t.start();
    try{
    Thread.sleep(1000);
    }
    catch(Exception e){}
    System.out.println("In Main");
    }
    }



    Similarly you can tweak the code to see that even if the main method
    throws Exception the MyThread run() method is not interupted and it produces its output before JVM exits.

    Thanks,
    Megha
    reply
      Bookmark Topic Watch Topic
    • New Topic