Results 1 to 3 of 3
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Having trouble catching exceptions

    This is my constructor:

    Java Code:
    	public Human(String name, int age) {
    		
    		System.out.println("A new human has been createad!");
    		this.name = name;
    		this.age = age;
    	}
    This is the code I am trying:

    Java Code:
    public void actionPerformed(ActionEvent arg0) {
    			try 
    			{
    				Human newHuman = new Human(inputNameTextField.getText(), Integer.parseInt(inputAgeTextField.getText()));
    			}
    			catch (Exception e) {
    				JOptionPane.showMessageDialog(null, "Please provide appropriate Name and age.","Something went wrong!", 0);
    			}
    		}
    When I put a string in the inputAgeTextField, I get no exception in the Command Line.

    And whether or not I put appropriate values in inputNameTextField and inputAgeTextField I always see the message in the catch block..

    Why is that parseInt not throwing an exception when there is a string in the inputAgeTextField ?

    Thank you..

  2. #2
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Having trouble catching exceptions

    nevermnd

  3. #3
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default Re: Having trouble catching exceptions

    Integer.parseInt(String text) throws NumberFormatException, you could handle it better like this:

    Java Code:
    int age;
    try {
        age = Integer.parseInt(intputAgeTextField.getText());
    } catch (NumberFormatException e) {
        System.err.println("Number format exception: " + e.getMessage());
        age = 0;
    }
    Then allow your program to continue with a default age value.

Similar Threads

  1. Catching Exceptions (quick question)
    By Danieldcc in forum New To Java
    Replies: 3
    Last Post: 02-19-2012, 11:40 PM
  2. catching exceptions (hierarchy)
    By kailash in forum Java Servlet
    Replies: 2
    Last Post: 02-10-2011, 06:43 AM
  3. Help with Catching Exceptions
    By javaman1 in forum New To Java
    Replies: 4
    Last Post: 09-11-2010, 02:06 AM
  4. Client catching Web Service User Exceptions [Java 6.0.17]
    By Shaitan00 in forum Advanced Java
    Replies: 4
    Last Post: 11-22-2009, 01:09 AM
  5. catching uncaught exceptions using Spring / WebApp
    By taille50 in forum Web Frameworks
    Replies: 1
    Last Post: 10-18-2009, 01:14 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •