Exception difficulty

Thread Starter

jakegwood

Joined Apr 13, 2011
29
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
 

Feign

Joined Mar 30, 2009
50
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(...)
 
Top