Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...
Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...
Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
CS151 Object-Oriented Design<br />
Dr. Kim<br />
{ try<br />
{ int a = args.length;<br />
System.out.println("a = " + a);<br />
int b = 42 / a;<br />
int [] c = { 5 };<br />
c[42] = 99 ;<br />
}<br />
catch (ArithmeticException e)<br />
{ System.out.println("Divided by 0: " + e);}<br />
catch (ArrayIndexOutOfBoundsException e)<br />
{ System.out.println("Array index oob: " + e);}<br />
finally<br />
{ System.out.println("This code is executed in anyway");}<br />
System.out.println(“xx”);<br />
}<br />
}<br />
• An exception h<strong>and</strong>ler recovers the problem, <strong>and</strong> has the program continues to run <strong>and</strong><br />
exit in a normal mode.<br />
import java.util.R<strong>and</strong>om;<br />
public class H<strong>and</strong>leError<br />
{ public static void main (String [] args)<br />
{int a = 0, b = 0, c = 0;<br />
R<strong>and</strong>om r = new R<strong>and</strong>om();<br />
for (int i = 0 ; i < 100; i++)<br />
{ try<br />
{ b = r.nextInt();<br />
c = r.nextInt();<br />
a = 12345/ (b/c);<br />
}<br />
catch (ArithmeticException e)<br />
{ System.out.println("Division by zero.");<br />
a = 0 ; // set a to zero <strong>and</strong> move on<br />
}<br />
System.out.println("a: " + a);<br />
}<br />
}//main<br />
}<br />
• When you use multiple catch statements, ensure that catch blocks h<strong>and</strong>ling subclasses<br />
come before those h<strong>and</strong>ling their superclasses. Note that a catch statement can h<strong>and</strong>le the<br />
specified class as well as it subclasses.<br />
class SuperSubCatch<br />
35