aspose file tools*
The moose likes Beginning Java and the fly likes Checked and Unchecked exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Checked and Unchecked exception" Watch "Checked and Unchecked exception" New topic
Author

Checked and Unchecked exception

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
Hello!
This is first time I post here,
It is said:
A checked exception tends to be something unusual but predicatable,
But We can predict that JVM error is possible.or lack of memory is possible,It is possible out of range of an array or�.
But if an error occurs about JVM,And program will be stop,it is unchecked error�
What do you mean by �predict�?

May you explain more about these?
You are not required to list any unchecked exceptions you might throw in the method signature. And when you call a method that might throw an unchecked the compiler won't see any "throws" clause, and won't force you to catch or handle the unchecked exception. For example, lots of methods might throw NullPointerException. You can catch them or not, the compiler won't care

If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
greg buela
Ranch Hand

Joined: Sep 04, 2007
Posts: 71
Hi,
Yes, JVM errors can happen, but unchecked exceptions are usually not meant to be especially considered by your application because you won't be trying to recover from them. They mean something really weird happened or there is a bug in your application that needs to be fixed. You can still catch and handle some unchecked exceptions, there may be reasons to do it sometimes, but it's not what you'd normally want to do. For example, array index out of bounds is always most likely a bug, so it's OK that it makes your app explode. You have to avoid bugs, not "handle" them.
Checked exceptions, in the other hand, are exceptions you normally want to recover from. They are things that may happen but doesn't mean your app has a bug, or that it should blow up. You want to catch them and react accordingly, instead of letting them propagate all the way up. These exceptions are normal to occur but your app is going out of its "normal flow". A common reason to go out of the normal flow is when something goes wrong with an external resource. For example, you are supposed to handle an unexpected end of file when reading a certain file format.


SCJP 1.5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39869
    
  28
I presume you have read the Java Tutorial about Exceptions?
You do realise that there are nearly as many different opinions about exceptions as there are different programmers?
Runtime Exceptions are called that because they occur entirely inside the Java runtime. Most (not quite all) runtime exceptions are (as Greg Buela has told you) the result of programming mistakes. Examples:-
  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • IllegalArgumentException
  • The correct response to any of those is to go back where they happen and find out whether there is a programming error.
    There are, however, a few runtime exceptions where the correct response might be to repeat the input, eg
  • InputMismatchException
  • NumberFormatException
  • These are probably worth catching.

    Other Exceptions occur at some sort of interface between the Java runtime and something else, or somewhere else. So an IOException might occur between the JVM and the operating system, or where there is a loose wire. If, for example there is a MalformedURLException, the usual response is to supply a correct URL, and a FileNotFoundException might require the right path for the file.
    [You can get a FileNotFoundException when the file is not available, maybe read-only, or locked by another application.]

    The idea is that every Exception which affects anything outside the JVM must be handled somehow.

    There are also Errors, which are caused by things beyond the control of a user when the program is running. If you have more objects than there is space for them, the program will crash. If you have a class missing, the program cannot run. Since these are impossible to recover from, Errors ought not normally to be caught.
    Note there are a few classes which are not really Errors but have slipped in, eg AssertionError, which you shouldn't catch, and ThreadDeath. ThreadDeath should be rethrown, so if you ever use a Threaded application and writeoryou should insertbefore the catch(Error).

    [edit]Sorted out UBB tags[/edit]
    [ September 07, 2007: Message edited by: Campbell Ritchie ]
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    . . . not that it is a good idea to catch an Error or a Throwable in the first place. You should simply let them propagate.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    . . . and welcome to the Ranch

    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello Again!

    Thanks for your nice welcome friends!

    If you have more objects than there is space for them, the program will crash. If you have a class missing, the program cannot run


    Say I've an application that uses too much memory and what you said hapend.

    1-May you describe the steps of process from moment that this happen until a user see an error on his screen?What does really do JAVA here?

    2-About Error class,It make me a little confuse ,May you explain more about How this class work?which errors do talk about in this case?(when you talk abpout error class)


    Thanks in advance!
    [ September 06, 2007: Message edited by: abalfazl hossein ]
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    To see an Error, try this:-
  • Set up an ArrayList<String> object.
  • Use its ensureCapacity() method to get a capacity of 1000000
  • Set up a for loop to add "Abalfazl" 1000000 times.
  • Use the ensureCapacity() method to increase capacity by 1000000
  • Surround the whole thing with a "while(true)" loop

  • Run it, and wait.

    Or, set up a constructor like this.Now there's a bit of bad programming if ever I saw it.

    For the Error class, look in the API, here, and here for Throwable. Follow the links in the API pages to Exception, etc.
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello

    1-What are differences between compile time Error and Runtime Error?

    2-http://java.ztor.com/fundamental/main/

    Handling Exceptions
    You can handle exception otherwise you must declare it. Also you can handle some exceptions and declare others.


    Handle Exceptions





    Declare Exceptions




    May someone explain more about difference between these?When do we use declare exception?When to use handel exception?
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello!

    Runtime Exceptions are called that because they occur entirely inside the Java runtime. Most (not quite all) runtime exceptions are (as Greg Buela has told you) the result of programming mistakes. Examples:-

    * ArithmeticException
    * NullPointerException
    * ArrayIndexOutOfBoundsException
    * IllegalArgumentException

    The correct response to any of those is to go back where they happen and find out whether there is a programming error.
    There are, however, a few runtime exceptions where the correct response might be to repeat the input, eg

    * InputMismatchException
    * NumberFormatException

    These are probably worth catching.



    http://java.sun.com/j2se/1.5.0/docs/api/java/util/InputMismatchException.html

    Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.


    Cann't we prevent this by a try in input?
    Then how can this happen?
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello

    http://www.nd.edu/~cwood1/teaching/java/JavaErrors.htm


    Java Errors


    IllegalAccessError

    An attempt was made to use a class, variable, or method which is not available to the calling class.



    When we compile a program that has a problem like this,It shows error..and force us to fix it..

    Then How is it possible something like that happen in Runtime?

    If it is possible,Please give me an example.

    Thanks in advance!
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello!

    Other Exceptions occur at some sort of interface between the Java runtime and something else, or somewhere else. So an IOException might occur between the JVM and the operating system


    May you explain about what operation system does when a JVM error happen?

    For example if out of memory happen,What does OS do?What does JVM do?

    Thanks
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello!

    Anyone answer my exception questions?
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    Patience will be rewarded . . . .


    A compile-time error means that the compiler has detected
  • a syntax error,
  • a class which can't be found (not imported),
  • attempted access to a private member of another class
  • etc etc.

  • Try these two classesTwo files, remember. Run them with
  • javac PrivateAccessDemo.java
  • java PrivateAccessDemo
  • Change the access in the PrivateAccess to "private void printMessage()" and compile PrivateAccess not PrivateAccessDemo. Now try running it.

    Remember your JVM is a system all of its own. Some things like division by zero occur inside the JVM and cause it to throw an Exception.
    If you are trying to access a file for reading, or a Stream for keyboard input, if anything goes wrong it is somewhere between the JVM and the operating system.

    You can handle or declare any type of Exception, or even re-throw an Exception. You declare an Exception when you think it is best handled elsewhere. Think:
  • What shall I do if XYZ happens?
  • Which method should best do that?
  • That will tell you where to handle it; if not here, then declare it, and handle it elsewhere.

    The ztor website is good about the different ways to handle Exceptions, but it is very brief. I think you will find the Java tutorial which I told you about on Thursday easier to understand. Note that the Java tutorial says "runtime exceptions are internal to the application."

    I have already told you there are many different opinions about Exceptions.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    The Jakarta people have a project called BCEL. Look on their website, and try ctrl-F then "exception". See whether that information helps.
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hi!

    May someone answer me please?Thanks in advance!
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    Have you tried any of my examples?
    Have you read the Java Tutorial?
    Have you looked in BCEL?
    Have you looked in any books?
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hi!

    Thanks for answer!

    It is said:

    You declare that a method throws an exception if the problem can't be handled in the method. You handle the exception in the method if you can handle the error and continue with the method.


    Please make it clear by an example.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    Go back to the ztor website you quoted earlier. It has a list of possibilities in, but they are very short. Where you throw and declare an Exception, and where you catch it, depend on the logic and structure of your application. So these things vary where you are.

    One possible example:-

    ApplicationData->"saveToFile()"->FileSaver class->File

    Apart from the fact that you want to close the BufferedWriter in a "finally" block:

    You can either declare the IOException in the save method and have the saveToFile method catch it, or have a try-catch in the save method.

    If saveToFile catches it:
  • The OuterClass object "knows" that saving failed.
  • The saveToFile method might try again, using a "savedOK" boolean flag and a "while" loop
  • You can store the file details in the OuterClass object.

  • If the FileSaver.save method catches it:
  • You can repeat attempts to save with the same or another file (again with a while loop)
  • You can return a boolean value to show whether it was saved correctly

  • Now, you decide which you think is better.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    You asked about InputMismatchException.

    Scanner throws an InputMismatchException if the token received and the token expected are incompatible. If you ask for myScanner.nextInt() and pass "123.45" or "abcde" it will throw an InputMismatchException. If you look in the API for Scanner, you find you can go back to the token.
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello!

    http://today.java.net/pub/a/today/2003/12/04/exceptions.html

    It isn't still clear for me advantage and disadvantage of declare exception and handle exception....

    May you give me a simple example,once by declare exception ,once by handle exception, and discuss about them....
    [ September 10, 2007: Message edited by: abalfazl hossein ]
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello!

    It is said:


    checked exception is it will be checked at the compile time .but unchecked exception is it only checked run time.


    You know that exception like filenotfound ,when you compile,if the file be lost,the compiler does not show error,Butin runtime,It makes Error...

    Then how do you say this:checked exception is it will be checked at the compile time?
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Hello


    If an exception is always handled using the throws clause, then eventually the exception will propagate all the way back to the main method of the application. If the main method throws the exception and the exception actually occurs while the program is running, then the program will crash.

    http://pages.cs.wisc.edu/~cs302/io/Exceptions.html

    If the main method throws the exception and the exception actually occurs while the program is running, then the program will crash?!Why?
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by abalfazl hossein:
    ...If the main method throws the exception and the exception actually occurs while the program is running, then the program will crash?!Why?

    How would an exception from main be handled?


    "We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
    sscce.org
    abalfazl hossein
    Ranch Hand

    Joined: Sep 06, 2007
    Posts: 635
    Is there anyone to answer my questions???!!
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39869
        
      28
    PatienceIsAVirtue

    Please, take it easy. We are trying to help you learn, not spoon-feed you; you don't learn anything from simple answers like that.

    The alternative to Exceptions is error codes, which were used in C; they mean the programmer or user has to check for errors when the program exits.
    If you don't believe it about Exceptions propagating, try writing a program with "throws" clauses on all the methods. Then do something which causes an Exception and wait.

    Checked Exceptions being checked at compile time means that the compiler insists there be some sort of handling written for every checked Exception. Other code might throw an unchecked Exception but the compiler won't insist on a try-catch.
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: Checked and Unchecked exception