Forum Stats

  • 3,815,605 Users
  • 2,259,059 Discussions
  • 7,893,185 Comments

Discussions

how to catch errors with a catch statments inside function?

3293553
3293553 Member Posts: 6
edited Nov 21, 2016 7:11AM in Swing

Hello  Oracle Users,

I have made a program

to calculate user date.

it works partali.

the problem is i added to it a catch function

that should catch errors.

the function has a try block and a catch block

and is located in anthor file called 'Err.java'

a refrence to the 'Err.java' file is "Err test_err = new Err();"

i added to the main java file called 'InputDate_catch.java'

also a 'try' and 'catch' statments

after the end of the try loop

and in the catch statment(in the main file)

i called the 'Err.java'(isDateFailed = test_err.err();)

where 'isDateFailed' is the boolen that should return true if error ocurred.

the function is called and all and all it does is return the "isDateFailed"

that's in the try block, and does not enters the catch statment

that are in the function, even if there are errors.

In short, My question is how can i pass the errors that eccours in the main program

to the function(Err.java)?

note: all this code is beetwen a 'do{' 'While{' loop,

         becuase I need it to loop in a specfic place if there's an error,

          and I need to redo it in specific places in the program.

Here is the Code for 'InputDate_catch.java':

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */import java.time.*;import java.time.temporal.ChronoUnit;import java.util.*;import java.time.format.DateTimeFormatter;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;/** * * @author User */public class InputDate_catch {    //private static Object p;    //private static Object p.getYears;                            /**     * @param args the command line arguments     * @throws java.lang.Exception in main metohod     */    public static void main(String[] args) throws Exception {        // TODO code application logic hereboolean isDateFailed=false;Err test_err = new Err();String age;        do{  try {isDateFailed=false; // reset's "isDateFailed" to false before catch errorage = JOptionPane.showInputDialog(null,"dd.MM.yyyy By:", "Type date of birth", JOptionPane.QUESTION_MESSAGE);        //if erro acoured  goes to 'catch statment' should return here with 'isDateFailed=true'//        }while(isDateFailed);  //loops if defined as 'true' in catch statment   /* All sorts of code:* ...* ...* ...* ...* ...* ...* ...* ...* ...*/int year_burn;        int birth_year;        int birth_months;        int days_burn;                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");        LocalDate d1 = LocalDate.parse(age,formatter);LocalDate dNow = LocalDate.now();  // Current date    Period p = Period.between(d1,dNow);long p2 = ChronoUnit.DAYS.between(d1,dNow);long p3 = ChronoUnit.WEEKS.between(d1,dNow);} // end of try statmentcatch(Exception ex){isDateFailed = test_err.err(); //catch function for error blocks, in seperate file called 'Err.java'}System.out.println("after age input and inside while loop isDateFailed= "+ isDateFailed); // for testing purposes only}while(isDateFailed);  //loops if defined as 'true' in catch statment        System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +" months, and " + p.getDays() +                    " days old. (" + p2 + " days total), (" + p3 + " Total Weeks)");/* all sorts of code:* ...* ...* ...* ...* ...* ...* ...* ...* ...* ...* ...* ...* ...* ...* ...*/  }}

P.S: if you try to compile the main file 'InputDate_catch.java' it will show an error of undefined varibales:(p.) and (p2) and (p3)

       I think it's becuase the varibles that define them are in 'do{' loop. and for some reason the rest of the program doesn't see them.

       In this I need help also.

And Here is the file Called('Err.java') that compiles good:

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * * @author User */import javax.swing.JOptionPane;public class Err {    boolean isDateFailed;    String strngtest;        /**     * 'param' below should start with '@'     * &param Nerr should be 1 if error true     * &param isDateFailed should be true if error true     * @return Nerr returns 1 if error ocuured     * @throws java.lang.Exception should catch errors     *      *      */    public boolean err() throws Exception { //after 'err()' maybe needed: 'throws Exception'          int Nerr;    boolean isDateFailed;                                                                                try{ isDateFailed=false;//Nerr = 1;//return Nerr;return isDateFailed;                          } // end of try statment   catch(NumberFormatException ex) {            System.err.println("NumberFormatException "+ ex.getMessage());            JOptionPane.showMessageDialog(null, ex.getMessage(), "System error in typed value", JOptionPane.ERROR_MESSAGE);            isDateFailed=true;            return isDateFailed;}catch(java.time.format.DateTimeParseException ex) {                              System.err.println("DateFormatException "+ ex.getMessage());            JOptionPane.showMessageDialog(null, ex.getMessage(), "Please type Value by shown strucure, bad value", JOptionPane.ERROR_MESSAGE);            isDateFailed = true;            return isDateFailed;                                    }catch(NullPointerException ex) {            System.err.println("NullPointerException "+ ex.getMessage());            JOptionPane.showMessageDialog(null, ex.getMessage() ,"System error missing value", JOptionPane.ERROR_MESSAGE);            isDateFailed = true;            return isDateFailed;                            }  }}

In short, I need help to learn how to pass erros to a function and that will catch it,

And how to use variables inside a 'do{' loop in a manner that they will still be seen outside the 'do{' loop.

Thank's a Lot,

Yaniv R.

Tagged:

Answers

  • TPD-Opitz
    TPD-Opitz Member Posts: 2,465 Silver Trophy
    edited Oct 14, 2016 12:56PM

    the state of your Err class object never gets altered.

    there is no parameter to the err() Method (in Java we do not distinguish between functions and procedures, just call them "methods") therefore your error object does not know about the error.

    Also:

    when you enter the catch block in your main() method you already know that an error happened, why would you call a different method to confirm that?

    bye

    TPD

  • 3293553
    3293553 Member Posts: 6
    edited Oct 15, 2016 5:31AM

    Hello TPD-Optiz,

    thanks for the reply.

    first I don't understand what parmater is not

    passed to the Err() class, if you can elebrate on that

    it will help me.

    and secondly i need a method to

    catch specific errors and to respond

    with specific error situation to the user.

    why am i using a separate method for this

    you ask, becuase i have more code in the program

    and every chunk of code neeed's it's own 'try{' & 'Catch{'

    statment's that are placed in beetwen 'Do{' & '}while' loop.

    and in this way i don't need to type every time

    in every 'do{' loop all the catch statments that are now in the Err() class.

  • 3293553
    3293553 Member Posts: 6
    edited Oct 18, 2016 10:21AM

    Hey all,

    Thanks for all the replays,

    but i still don't know how to make

    a catch statments inside a method.

    TPD-Optiz, posted something, but i didn't

    understand him, and his not replaying a long time now.

    if someone can help me and explain

    how to make catch statments inside a method,

    and how to call that method,

    it will be very helpfull.

    Thanks,

    Yaniv R.

  • jduprez
    jduprez Member Posts: 2,457
    edited Nov 21, 2016 7:11AM

    Hello,

    first I don't understand what parmater is notpassed to the Err() class, if you can elebrate on thatit will help me.

    Well, when executing a method, the Java program knows only:

    - the values of instance fields of the current object

    - the value of static fields of the current class

    - the value of public static fields of other classes (this is oversimplified, but you get the idea)

    - the values of arguments of the current method

    - if these arguments are themselves objects (in all strictness: references to objects), the values of public instance fields of these objects (this is oversimplified, but you get the idea)

    - the local variables of the current method or block of code

    - in a catch block, the exceptions caught by the catch statement

      -- In your err() method, no exception is thrown, so your catch clause would catch nothing (I guess your compiler declares that).

    In summary, the exceptions thrown in your main method match none of the categories above, so they are not visible to err() method.

    3293553 wrote:why am i using a separate method for thisyou ask, becuase i have more code in the programand every chunk of code neeed's it's own 'try{' & 'Catch{'statment's that are placed in beetwen 'Do{' & '}while' loop.and in this way i don't need to type every timein every 'do{' loop all the catch statments that are now in the Err() class.

    If all those loops are in the same method, you could just enclose them all in a single try/catch construct.

    If not, well, I doubt that factoring catch statements would bring any productivity gain, as there is already a structural duplication of your program's logic.

    Eventually, this is a Swing forum, and this topic has nothing to do with Swing, your questions relate to learning Java language. I suggest posting in   instead.

    Best regards,

        J.

This discussion has been closed.