


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



public class UnderZeroException extends Exception { public UnderZeroException (String m){ super(m);} } public class ZeroException extends RuntimeException { public ZeroException(String m) { super(m);} } public class ExceptionExercise{ private int[] numbers = {1,-3,-5,0}; private int x; public void method1(int y) throws UnderZeroException { System.out.println("Start of method1"); int temp = numbers[y]; x= y+1; if (temp <0) throw new UnderZeroException("method1:The number is negative!"); else if(temp == 0) throw new ZeroException("method1:The number is zero"); System.out.println("End of method1"); } public void method2(int n) throws UnderZeroException { System.out.println("Start of method2"); try{ method1(n);} catch(UnderZeroException e) { System.out.println(e); if(x>2) throw e; else throw new UnderZeroException("method2:The number is negative!"); } finally {System.out.println("Finally in method2");}
System.out.println("End of method2"); } //------------------- public static void main(String[] args){ System.out.println("Start Of main"); ExceptionExercise ex = new ExceptionExercise(); try{ // ... The body of try } catch(ZeroException e) { System.out.println(e.getMessage());} catch(UnderZeroException e) { System.out.println(e.getMessage()); System.out.println("Caught in main"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("End of main"); } }
public class GreaterThan0 extends Exception {…} public class GreaterThan6 extends GreaterThan0 {…} public class GreaterThan11 extends GreaterThan6 {…} public static void main (String [] args) { Scanner input = new Scanner (System.in); int x = input.nextInt(); try{ try{ if(x>11) throw new GreaterThan11(); else if (x >6) throw new GreaterThan6(); else if (x>0) throw new GreaterThan0(); } catch (GreaterThan6 e) {System.out.print ("GreaterThan6 caught");} } catch (GreaterThan11 e) {System.out.print ("GreaterThan11 caught");} catch (GreaterThan0 e) {System.out.print ("GreaterThan0 caught");} } }