Exception not being thrown in try statement

I am trying to write a small program to handle exceptions. However, the program will not compile because it is giving me an error saying the exception InvalidDocumentCodeException will never be thrown in body of coresponding try statement. Here are the two programs:
public class InvalidDocumentCodeException extends Exception {
InvalidDocumentCodeException (String message) {
super(message);
and
import java.util.Scanner;
public class Main2 {
// Creates an exception object and possibly throws it.
public static void main (String[] args) {
char designation;
String input = null;
int valid = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a 2-digit designation starting " + "\n" +
"with U, C, or P, standing for unclassified, " + "\n" +
"confidential, or proprietary: ");
input = scan.nextLine();
try {
designation = input.charAt(0);
if(designation == 'U')
valid++;
else if(designation == 'C')
valid++;
else if(designation == 'P')
valid++;
else if(designation == 'u')
valid++;
else if(designation == 'c')
valid++;
else if(designation == 'p')
valid++;
catch (InvalidDocumentCodeException problem) {
System.out.println("Invalid designation entered " +
problem);
System.out.println ("End of main method.");
can anyone tell me what I am doing wrong here?

kenporic wrote:
Forgive me, This is the first time I have used this sight and I should have been more precise. Thanks for all the help, but this is an excercise in how to handle exceptions in Java. One way is to "throw" the exception to another class to be handled. The other is to handle the exception within the running class. The throws program That I have works. The problem that I am having is handling the exception within the class without coding the "throws" statement. I am supposed to use the try-catch method in doing this. In the example I was given to follow, the code did not specifically throw the exception. If the input was not handled in the processing code then the catch statement is supposed to call to the exception class somehow?Okay, there are two families of exceptions--checked and unchecked.
Checked: These are for things that are not part of the "happy path" of your code, but that your code may reasonably be expected to deal with. They're not necessarily signs of a bug in your code, nor do they indicate a problem in the JVM that's beyond your control. They're for things like when a file you're looking for doesn't exist (so maybe you handle it by asking the user to pick a different file), or a network connection being lost (so maybe you handle it by waiting a few seconds and trying again).
When a checked exception occurs, since it's an expected and recoverable occurrence, you're expected to deal with it. So, when one of these exceptions can occur in your method, your method is required to either a) handle it (with catch) or b) let the caller know that HE might be asked to deal with it.
We must either handle it:
void doFileStuff(String path) {
  try {
    do file stuff
  catch (IOException exc) {
    retry--which means the whole try catch would be in a loop
    or maybe just substitute some default values that don't have to come from a file
}Or let our caller know that he's going to have to handle it (or pass it on to his own caller):
void doFileStuff(String path) throws IOException) {
  // this might throw an exception, but it's not this method's job to handle is, so it bubbles up to our caller
  do file stuff;
Unchecked: These are things that are either bugs in your code (like a NullPointerException) or serious problems with the JVM that are beyond our control (like OutOfMemoryEror). These can occur anywhere, and it's not generally our code's job or our caller's job to deal with them, so they don't need to be caught or declared like checked exceptions do. You can catch them, and there are some places where it's appropriate to do so, but leave that aside for now.
Unchecked exceptions are RuntimeException, Error, and every class that descends from them. Checked exceptions are everything else under Throwable, and Throwable itself.
Now, when you do
void foo() throws SomeException {You're telling the compiler that this method might throw that exception.\
If SomeException is a checked exception, the compiler is able to tell whether your claim that you might throw it is true. Since it's checked, every method that might throw it must declare it. So the compiler can look at all the methods you call and see if they throw SomeException. If none of them do, and you don't explicitly put throw new SomeException(...); in your foo() method, then the compiler can be absolutely sure that there's no way foo() will throw SomeException. So it won't let you claim to throw it.
On the other hand, is SomeException is unchecked, then since methods aren't required to report the unchecked exceptions they can throw, the compiler has no way of knowing whether some method you call might throw SomeException, so it always lets you declare it (and never requries you to).

Similar Messages

  • Exception not being thrown

    I added code to throw an exception when a user-initiated search returned no rows, but for some reason, the exception isn't being raised on the browser. Code:
    mnVo.setWhereClause(queryparams);
    mnVo.executeQuery();
    if(mnVo.first() == null)
    throw new oracle.jbo.JboException("No records on file");
    If I step through the code, I see the throw statement executing, but it is never surfaced. What does get raised is:
    JBO-29000: Unexpected exception caught: java.lang.ArrayIndexOutOfBoundsException, msg=0
    This gets raised (apprently) outside of my code, and the debugger can't find it. What do I need to have in place in order to handle this condition?

    I'm a java newby, so I 'think' I understand what you mean, and I 'think' I already did? Here's the code now:
    if(mnVo.first() == null)
    throw new oracle.jbo.JboException("No records on file");
    catch (Exception e)
    { throw new oracle.jbo.JboException("No Records Found");}
    This behaves identically as it did before...I can see it being thrown in the debugger, but the browser never gets it, and it gets the other error which is pretty non-sensical to a user.
    I failed to mention earlier that this code is in the Application Module in the Client Interface, in case that makes a difference?

  • Thrown validation exception not being showed in jspx page

    Hi,
    I have a page with af:table which uses one view object.That view object is using one entity object. In one of the method of the EntityImpl class of my entity object i throw ValidationException.I debugged the application and i saw that it is throwing the exception.But it is not being shown in the page. What might be wrong here?
    try{
    setAttributeInternal(BANKTYPE, value);
    catch(TooManyObjectsException e) {
    e.printStackTrace();
    throw new ValidationException ("You are trying to add existing record");
    My jspx page is having *<af:messages id="m1"/>*
    Does the jspx page need any configuration to show the thrown exception in a popup?
    Regards,
    Priya.

    Hi vinod,
    I tried it and it worked.Thanks a lot :). Can you please tell me why it was not happening with the ValidationException?
    Regards,
    Priya.

  • Exception is being thrown

    I tried out this small code for using hashset but it gives exceptions. I have no idea why is it so?
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    class Students implements Comparable
         private String name;
         private float gpa = 0.0F;
         Students(String n, float g)
              name = n;
              gpa = g;
         Students(){}
         public String getName() {
              return name;
         public float getGpa() {
              return gpa;
         @Override
         public int compareTo(Object o) {
              // TODO Auto-generated method stub
              if(this.getGpa() > ((Students)o).getGpa())
                   return 1;
              else if(this.getGpa() < ((Students)o).getGpa())
                   return -1;
              else
                   return 0;
         public boolean equals(Object o){
              if(this.getGpa() == ((Students)o).getGpa())
                   return true;
              else
                   return false;
         public int hashCode(){
              return (int)(10*gpa);
    public class HashFunction {
         public static void main(String args[]){
              Students s1= new Students("Fred", 3.0F);
              Students s2 = new Students("Sam", 3.1F);
              Students s3 = new Students("Steve", 3.5F);
              Set s = new HashSet();
              s.add(s1);
              s.add(s2);
              s.add(s3);
              Iterator i = s.iterator();
              while(i.hasNext())
                   System.out.println(((Students)i.next()).getName() + " " + ((Students)i.next()).getGpa());
    }The exception trace that is generated is as follows:
    Exception in thread "main" java.util.NoSuchElementException
         at java.util.HashMap$HashIterator.nextEntry(HashMap.java:796)
         at java.util.HashMap$KeyIterator.next(HashMap.java:828)
         at HashFunction.main(HashFunction.java:68)

    roaan wrote:
    I had one more question. I am reading from the file like this
              String word;
              word = file.nextWord();
              try{
                   while(word != null)
                        word = word.toLowerCase();
                        wf.put(word);
                        word = file.nextWord();
              catch(Exception e){
                   e.printStackTrace();
         }Now when the end of the file is reached word contains null and throws a nullpointer exception. I am catching that exception but is there a way out that when my word is null i should simply exit out of the loop (i check that word is not equal to null in my while loop but still it throws an excpetion).Nothing there can throw NPE from word being null. The only possibilities of NPE in the code you posted are
    1. if file is null
    2. if wf is null
    3. if NPE is being thrown inside nextWord(), which has nothing to do with word being null.
    Once you make sure that the above are not happening, that code will be fine and you won't need to catch NPE. And in fact, catching NPE like that is bad practice anyway.

  • Index not being used in Select statement

    Friends
    I have the following SQL statement:
    SELECT
    a.acct,
    a.date_field,
    UPPER(b.feegroup) feegrp,
    SUM (a.fee1) fee1,
    SUM (a.fee2) fee2,
    SUM (a.fee3) fee3
    FROM table1 a, table2 b
    WHERE 1 = 1
    AND a.fee_id = b.fee_id
    GROUP BY a.acct, a.date_field, b.feegroup;
    Both the tables have index on fee_id column. When I run the explain plan for this statement, I am getting the following output:
    Operation | Option | Object Name | Position
    SELECT STATEMENT | | | 560299
    HASH | GROUP BY| |1
    TABLE ACCESS | FULL| table2 | 1
    TABLE ACCESS | FULL| table1 | 2
    Why Oracle is not using the index?
    Edited by: darshilm on Dec 10, 2009 3:56 PM

    The proposed plan is the optimal according to your current conditions in the "where clause" where you have only the equality join condition and therefore the CBO can use HASH JOIN. Using any kind of index access would just increase the amount of required work unless you would add some very restrictive conditions which will select rows from relatively small amount of blocks. Here I have to mention that what really counts in the CBO cost calculation is the amount of blocks accessed and not the number of rows. The "currency" for I/O in Oracle is a block and not a row. CBO always uses an assumption that there is nothing in the buffer cache and it will have to perform a physical read for every block.
    How many blocks will actually be accessed depends on the data distribution. It can happen that every single row that you have to retrieve resides in a different block and although you access only 1000 rows out of a million row table you would have to visit almost every block of that table. For such a situation a FULL TABLE SCAN is the best access path and Oracle will use multiblock I/O for that. On the other side you can have those 1000 rows only in a few blocks and then the index access would be the most appropriate one. For index access Oracle uses single block I/O. Usually the actual situation is somewhere between this two extreme situations. But you can run some tests by yourself and see when an index access will be replaced by a full table scan while you will make your predicates less selective.
    HTH, Joze
    Co-author of the forthcoming book "Expert Oracle Practices"
    http://www.apress.com/book/view/9781430226680
    Oracle related blog: http://joze-senegacnik.blogspot.com/
    Blog about flying: http://jsenegacnik.blogspot.com/
    Blog about Building Ovens, Baking and Cooking: http://senegacnik.blogspot.com

  • SQLException(original cause) in throw new EJBException(SQLException) is being lost, when the remote exception is being thrown by the container (ejbStore()) in IPlanet. Works in WL and WS

    (IPlanet 6 - SP4)
    we have something like this in the EntityBean :
    ejbstore()
    try {
    myDAO.Update();
    catch(SQLException se)
    throw new EJBException(se);
    But in the SessionBean, where we set the detail (which
    causes ejbStore() to fire), I'm seeing a TransactionRolledBack exception with no trace of the
    original exception within it (The "detail" attribute
    too is null ). The same thing works in WL and WS.
    Any suggestions appreciated.

    Turn your checked exceptions into unchecked exceptions and retrieve the cause later:
    RuntimeException unchecked = new RuntimeException(checked);
    Throwable t = unchecked.getCause();Stephen

  • Exception OrderException is never thrown in body of corresponding try state

    Currently, I have a problem with a throwing an exception that I created. No matter what I try, it continues to give me this error. My code is below and I cannot figure out what I am doing wrong. Any suggestions??
    public class OrderException extends Exception
         public OrderException(String s)
              super(s);
    public class ExceptionOrder extends JFrame implements ActionListener
    //my code creates items in JFrame
         public ExceptionOrder()
              //creates JFrame
         public class Order
              String itemNumber = new String();
              int itemNum;
         public Order(String itn, int itnum) throws OrderException
                   itemNumber = itn;
                   itemNum = itnum;
                   //itemQuantity = itq;
                   if((itnum <= 111) || (itnum >= 999)) throw(new OrderException(itn));
         public void actionPerformed(ActionEvent e)
              int numItem;
              int itemPrice;
              int itemQuantity;
              itemPrice = 1;
              try
              numItem = Integer.parseInt(item.getText());
              itemQuantity = Integer.parseInt(quantity.getText());
              itemPrice = itemQuantity * 2;
              price.setText(String.valueOf(itemPrice));
              catch(OrderException e2)
              //DOES NOT LIKE OrderException
              //says we did not throw OrderException in try statement
              //when run with a JAVA Exception, like NumberFormatException
              //program runs
                   System.err.println("Invalid Item Number or Quantity");
                   //itemPrice = itemQuantity * 2;
    any thoughts/suggestions??

    I'm not sure what you are asking. Can you please
    eloborate? I have a class named Order that I am
    trying to throw my exception if the itNum is <=111 or
    =999. I'm not sure what you mean...
    Throwing an exception is a property of a function or a constructor, not of a class. So if you don't use the constructor of the class Order in your try-statement no OrderException can be thrown.

  • My Canon PIXMA MG2440 USB is not being recognised and I can not print anything..?

    I cannot use my printer as the USB is saying its not recognised.
    I never needed a driver for this printer before and it used to work fine. 
    I have no idea how to get my printer to work as I cant connect it to my laptop?

    Hi mrsrsimmo,
    If the printer is not being recognized, please try connecting the printer to another USB port on your computer, and also use a different USB cable if you have one.  We also recommend installing the latest drivers and software for the printer.  Since you have the PIXMA MG2440, please click here to go to the Support and Downloads page on the Canon Europe website where you can download the drivers.
    Hope this helps!
    Did this answer your question? Please click the Accept as Solution button so that others may find the answer as well.

  • This exception is never thrown from the try statement body

    try {
                   SimpleFileReader.openFileForReading("fileName.text");
              } catch (FileNotFoundException fnfe) {
                   System.out.println("");
              }This is part of a method, if that helps. In Eclipse I get the error message "Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body." I saw another post similar to this one, but it's not quite clear what the solution is. Could anyone clarify for a beginner?
    Thanks

    It actually does if the file it's opening is not really a text file, or if it's read-protected. Or is that where I'm going wrong? I'm just trying to open the file's name(already in the field) and know that it is .text or will return the error.
    Edited by: meme_kun_345k on Jan 15, 2008 7:18 PM

  • Exception not thrown on Key Exists

    using c# api:
    I have a Btree DB configured with two secondary DB's and a custom comparer, I have initialized the DB with 'DuplicatesPolicy.NONE'. To my understanding this should cause an exception to be raised if I try to enter a duplicate. On Put(), I get no such exception.
    Why? Am I supposed to throw this from comparer? (Actually tried this but it looks like it leaves cursor in undefined state). How Do I get the KeyExists Exception to be raised when a key exists???
    To my understadning I cannot use PutNoDuplicate() as a primary with secondaries cannot have duplicates configured, and you can only use PutNoDuplicate if there is a sorted duplicate policy...
    Any suggestions?

    Hi,
    The documentation could be a little misleading here. If you specify DuplicatesPolicy.NONE for a database, then duplicates will not be allowed in the database, and when trying to put a key/data pair in the database when the key already exist will fail:
    "Insertion when the key of the key/data pair being inserted already exists in the database will fail. "
    Failing here means that there will be no duplicate created, without any exception being thrown as the default behavior is to "Store the key/data pair in the database, replacing any previously existing key if duplicates are disallowed"; see the Database.Put() methods (BTreeDatabase extends from / is a sub-class of Database).
    You should use the PutNoOverwrite method. When the key that your are trying to insert already exists in the database, you will get a KeyExistException exception.
    Regards,
    Andrei

  • My toshiba external hard drive is not being recognized, except when I eject it. I have the preferences checked to show icon and have checked utilities folder. nothing. Help!

    I have a iMac, Yosemite 10.10 and my toshiba external hard drive is not being recognized, except when I eject it!. I have the preferences checked to show icons and have looked in the utilities folder..nothing. I have also changed ports. ??

    A few things to try:
    1-Repair permissions and restart your computer.
    2-Zap the PRAM
    3-Use Software Update/App Store to update your OS to OS 10.10.3.  Also, update everything SU/AS has to offer for your computer.  When done, repair permissions and restart your computer. 

  • Wait - interrupt  Why Exception not thrown?

    Hello. I expected that calling interrupt() on a waiting thread should result in InterruptedException thrown by wait(). Nevertheless, in the code below no Exception is thown as if there were no interrupt() call. Actually this snippet prints the same output irregardless of whether interrupt() is called.
    public class Runner {
        synchronized public void foo(){
            System.out.println("before wait in foo()");
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println("InterruptedException");
                e.printStackTrace();
            System.out.println("after wait in foo()");
        synchronized public void bar(){
            System.out.println("before sleep in bar()");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            System.out.println("after sleep in bar()");
            notify();
            System.out.println("after notify in bar()");
        public static void main(String[] args) {
            final Runner runner = new Runner();
            Thread t1 = new Thread(new Runnable(){
                public void run() {
                    runner.foo();
            Thread t2 = new Thread(new Runnable(){
                public void run() {
                    runner.bar();
            t1.start();
            t2.start();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            t1.interrupt();
            System.out.println("t1 interrupted");
    }

    Thanks for your response.
    Still the whole thing is not clear to me.
    Why InterruptedException is not deterministic in this
    case?
    Where is the ?non-deterministic? code in this
    example?The fact that t1.start() is written before t2.start() in you code does not guarantee that foo() method will always be called first. Either the bar() method or foo() method can be invoked firstly, because this is how threads work in Java. Try to invert: put t2.start() before t1.start(), and see what happens. Probably the exception will be thrown in this case, but this behaviour is still non deterministic.
    Please pay attention to timing -
    t1.interrupt() is called in about 5 seconds after
    both threads are started, at the time when one thread
    is in sleep(10000) and the other in wait(). I believe
    that above condition may be taken for granted taking
    in account 5 seconds interval between calls.You know that when you invoke the notify() method inside the bar method() you are making the foo() method not waiting anymore, don?t you? Therefore, if foo() method is called firstly, then the InterruptedException probably won?t be thrown. I said "probably" because the behaviour is non deterministic. Time is relative. If your processor is fast, then probably the exception will never be thrown, but you will never be completely sure. Maybe if there are other executions using your processor, then the processor might be slow for your program, and then the InterruptedException might be thrown. If you want to make your program have the same behaviour always, then you have to use semaphore variables, that indicate when exactly one thread is permitted to run.

  • Global exception handler not being called

    Hi,
    I have a wli process that has a global excepton handler. One of the controls throws a NullPointerException but it is not being handled by the group exception handler nor the global exception handler.
    Does anyone have any idea what may be causing this behaviour?
    Thanks,
    Dale

    I have discovered that using -memalign=Ns with N greater than 1 does not work for me. For example, if I remove a VME card from the system and try to use an unsigned short pointer to access a 16-bit register in the card's vacated VME address space, my signal handler gets called when I compile the code with N=1, but for any other N, my handler is ignored and my program cores.
    Unfortunately, using N=1 causes other code that works with higher N to fail. I have one VME card where I need to access a register as a 16-bit read. The code the compiler generates to access the unsigned short pointer value results in two single-byte load instructions - this causes the device to cry foul and as a result, the driver raises SIGBUS, which my program handles. For higher N, the compiler generates one two-byte load instruction, and the device is happy to send back the data.
    So it would appear there is some kind of problem with -xmemalign=Ns for N > 1. It seems like the SIGBUS handler typically imployed by the compiler to handle the misalignment problems when -xmemalign=Ni is used is being invoked.
    Any other ideas?

  • Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --- System.NullReferenceException: Object reference not set to an instance of an object

    Hi,
    (1) I am trying to get the data from a database table and import into a text file.
    (2) If the record set have the data then it runs ok
    (3) when the record set not having any data it is giving the below error
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object
    Could you please let me know why this is happening?
    Any help would be appriciated
    Thanks,
    SIV

    You might ask them over here.
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vbgeneral%2Ccsharpgeneral%2Cvcgeneral&filter=alltypes&sort=lastpostdesc
    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]
    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

  • Ipad is not being recognized by Windows..I get a Code 43 error on any USB port I try. I have rebooted, restarted, blah blah til I am blue in the face.

    Ipad is not being recognized by Windows..I get a Code 43 error on any USB port I try. I have rebooted, restarted, blah blah til I am blue in the face. This is an Ipad not an Ipad2...I can't get this thing recognized by either my desktop or laptop. It used to work...not now.
    Any ideas?

    Did you already have a look at this article?
    iOS: Device recognized in iTunes for Mac OS X

Maybe you are looking for

  • Best Practices for new iMac

    I posted a few days ago re failing HDD on mid-2007 iMac. Long story short, took it into Apple store, Genius worked on it for 45 mins before decreeing it in need of new HDD. After considering the expenses of adding memory, new drive, hardware and inst

  • Process of debit of duty in case of purchase return

    DEar all, can i have the system customised in such a way that for the scenario of debit of duty in case of purcase return , the debit should happen to rg 23 part2 . And if there is no balance then it should debit rg23 c part 2 and if there is a no ba

  • CPAM 1.2 to 1.3 Uprade Stuck

    Has anyone seen a 1.3 upgrade get stuck? I'm working on our lab CIAC-PAME-1125 and it got stuck after the reboot. Web Admin output is: This page will get refreshed automatically in 5 seconds. Starting post upgrade steps.                   Done Initia

  • How to stop this wretched programme messing my desktop

    I followed the instructions to what I thought was to upgrade adobe reader. In addition, I also got this Acrobat.Com thing. I didn't ask for it. I'm sure its a fine programme...BUT the folder always opens up onto my desktop when I start the computer,

  • Variable Conversion

    I am a college student, learning Java programming. The program I'm working on now has to do with drawing a graph, given the height and width of the widow and the max and min x-values. For my calculations, I have my variables in doubles, but to plot o