-2

i seem to be a bit confused on how to throw exceptions and when it would be used to create your own exceptions.

i have this code and was wondering if i went about this the correct way

heres the method:

public void setHireYear(int year) throws Exception {
    try{
        if (year <= CURRENT_YEAR && year >= CURRENT_YEAR - MAX_YEARS_WORKED) {
            hireYear = year;
        }
        else{
            throw new HireYearException(year);
        }
    }catch(HireYearException e){
        e.toString();
    }
}

and heres the exception class:

public class HireYearException extends Exception
{

private int hireYear;

/**
 * Constructor for objects of class HireYearException
 */
public HireYearException(int hireYear)
{
   this.hireYear = hireYear;
}


public String toString()
{
   return "Hire year cannot exceed Current year, your hire year is - " + hireYear;
}
}

why would throwing a custom exception be better than throwing pre defined exceptions?

davedno
  • 349
  • 1
  • 5
  • 15
  • You should not `catch` your own exception in the throwing method, if you catch it it means you can solve the problem locally, so there is no need for the exception anymore, otherwise propagate the exception to the caller and let one of the calling methods handle the exception. So ommit the try-catch block in the method. – tomse Apr 24 '15 at 19:04
  • Why a custom exception isn't better than a pre-defined exception? – aldux Apr 24 '15 at 19:04
  • 1
    1./ Validation should not be checked by catching Exceptions, use separate validation logic. GUI and Web Frameworks typically help you in that; 2./ If you are expected to have separate validation logic, then an invalid argument choice is programmer error: use IllegalArgumentException – YoYo Apr 24 '15 at 19:15

1 Answers1

0

Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this:

try
{}
catch (Exception ex)
{}

This catches all exceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for each type:

try
{}
catch (CustomException1 ex1)
{
    //handle CustomException1 type errors here
}
catch (CustomException2 ex2)
{
    //handle CustomException2 type errors here
}
catch (Exception ex)
{
    //handle all other types of exceptions here
}

Hence it provides you (benefits and why to create it)

1.specific exceptions allow you a finer level of control over your exception handling

2.Provides a type safe mechanism for a developer to detect an error condition.

3.Add situation specific data to an exception Ideally this data would help another developer track down the source of the error.

4.No existing exception adequately described my problem

Source

Community
  • 1
  • 1
Ankur Anand
  • 3,873
  • 2
  • 23
  • 44