Personally think first to know two points:
1. The parent class of the exception is Throwable
2. Errors, exceptions are divided into three categories, but only one of the procedures required to process
Now write a small example:
Requirements: Both sides of the respective heroes to attack, if a person's health value reaches 0, the other side to attack, then reported that the hero is dead, unable to continue the attack exception:
1 Packagejavatest;2 3 classEnemyheroisdeadexceptionextendsException {4 Publicenemyheroisdeadexception () {}5 6 Publicenemyheroisdeadexception (String msg) {7 Super(msg);8 }9 }Ten One Public classHero { A PublicString Heroname; - protected floatLifePoint; - the Public voidAttackhero (Hero h)throwsenemyheroisdeadexception { - if(H.lifepoint = = 0) { - Throw NewEnemyheroisdeadexception (H.heroname + "Hero has been dead"); - } + } - + PublicString toString () { A returnHeroname; at } - - Public Static voidMain (string[] args)throwsenemyheroisdeadexception { -Hero Galan =NewHero (); -Galan.heroname = "Galan"; -Galan.lifepoint =0; in -Hero Mike =NewHero (); toMike.heroname = "Mike"; +Mike.lifepoint =10; - the Try { * Mike.attackhero (Galan); $}Catch(enemyheroisdeadexception e) {Panax NotoginsengSYSTEM.OUT.PRINTLN ("Specific reason" +e.getmessage ()); - e.printstacktrace (); the } + } A}
The above code shows a process for writing a custom exception:
1. Write an exception class, inherit exception
2. In place of the call, catch the custom exception with a try Catch
3. Invoke a statement in try that may throw an exception
Java Basics-Custom exception usage exercises