Exception difficulty

Discussion in 'Programmer's Corner' started by jakegwood, Nov 12, 2011.

  1. jakegwood

    Thread Starter New Member

    Apr 13, 2011
    29
    0
    I have an assignment where I have to sort an array objects of person, teacher and student class (student and teacher are both subclasses of person), first by category (Person, Teacher, Student) then do other sorting, but my main issue is with the first task.

    class Person
    {
    int age;
    //constructors
    }

    class Teacher extends Person
    {
    int Salary;
    //constructors
    }

    class Student extends Person
    {
    int gpa;
    //constructors
    }

    We are not allowed to use instanceof, so I was thinking to figure out what each object is test it for certain Parameters using try catch. So for instance, if I am looking for People in the array, I could try to operate on person.gpa and person.salary, neither of which exists, which throws the cannot find symbol, and if that error is caught for both variable, I would know that that Person is only a Person, not a Student or Teacher. However, when I write the code, my catch statement won't catch the error. I simplified things, to a basic try-catch and the exception still was not being caught. Here's my simplification:

    public class test2
    {
    public static void main(String args[])
    {
    try
    {
    int x = y;
    }
    catch(Error er)
    {
    int x =0;
    }
    }
    }

    If you could help me figure out how to catch the error (that y doesn't exist) that would be great, because mine won't catch.

    Thanks
     
  2. Feign

    Active Member

    Mar 30, 2009
    50
    2
    y not existing is a compiler error, isn't it? but then you don't actually say what language you are using.

    What language is this?

    "Beware of instanceof operator"
    http://www.javapractices.com/topic/TopicAction.do?Id=31

    They say you can not use instanceof but it's still a useful read. The Object in this case Person should maybe know how to sort() it's self?

    At anyrate you're looking for a casting exception if you can't/don't alter the class's.

    catch(ClassCastException& e) or catch(std::bad_cast& e) worst case catch(...)
     
Loading...