java - Correct way to handle method exception? -


this question has answer here:

i seem bit confused on how throw exceptions , when used create own exceptions.

i have code , wondering if went correct way

heres 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 exception class:

public class hireyearexception extends exception {  private int hireyear;  /**  * constructor objects of class hireyearexception  */ public hireyearexception(int hireyear) {    this.hireyear = hireyear; }   public string tostring() {    return "hire year cannot exceed current year, hire year - " + hireyear; } } 

why throwing custom exception better throwing pre defined exceptions?

specific customs exceptions allow segregate different error types catch statements. common construct exception handling this:

try {} catch (exception ex) {} 

this catches exceptions regardless of type. however, if have custom exceptions, can have separate handlers each type:

try {} catch (customexception1 ex1) {     //handle customexception1 type errors here } catch (customexception2 ex2) {     //handle customexception2 type errors here } catch (exception ex) {     //handle other types of exceptions here } 

hence provides (benefits , why create it)

1.specific exceptions allow finer level of control on exception handling

2.provides type safe mechanism developer detect error condition.

3.add situation specific data exception ideally data developer track down source of error.

4.no existing exception adequately described problem

source


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -