10.Create a class with two methods, f() and g(). In g(), throw an exception of a new type that you define. In f(), call g(), catch its exception and, in the catch clause, throw a different exception (of a second type that you define). Test your code in main().
package job;
import java.util.*;
public class Main {
static void f() throws Exception {
try {
g();
}catch (Exception e){
e.printStackTrace(System.out);
System.out.println("throw from f()");
throw new Exception("way of f()");
}
}
static void g()throws Exception{
System.out.println("throw from g()");
throw new Exception("way of g()");
}
public static void main(String[] args) {
try {
f();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
output:
throw from g()
java.lang.Exception: way of g()
at job.Main.g(Main.java:15)
at job.Main.f(Main.java:6)
at job.Main.main(Main.java:19)
throw from f()
java.lang.Exception: way of f()
at job.Main.f(Main.java:10)
at job.Main.main(Main.java:19)
11.Repeat the previous exercise, but inside the catch clause, wrap g()'s exception in a RuntimeException.
package job;
import java.util.*;
public class Main {
static void f() throws Exception {
try {
g();
}catch (RuntimeException e){
e.printStackTrace(System.out);
System.out.println("throw from f()");
throw new Exception("way of f()");
}
}
static void g()throws RuntimeException{
System.out.println("throw from g()");
throw new RuntimeException("way of g()");
}
public static void main(String[] args) {
try {
f();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
output:
throw from g()
java.lang.RuntimeException: way of g()
at job.Main.g(Main.java:15)
at job.Main.f(Main.java:6)
at job.Main.main(Main.java:19)
throw from f()
java.lang.Exception: way of f()
at job.Main.f(Main.java:10)
at job.Main.main(Main.java:19)
12.Modify innerclasses/Sequence.java so that it throws an appropriateexception if you try to put in too many elements.
package job;
import java.util.*;
interface Selector {
boolean end();
Object current();
void next();
}
public class Main {
private Object[] items;
private int next = 0;
public Main(int size) {
items = new Object[size];
}
public void add(Object x) throws Exception {
if (next <= items.length)
items[next++] = x;
if (next > items.length) {
throw new Exception();
}
}
private class SequenceSelector implements Selector {
private int i = 0;
public boolean end() {
return i == items.length;
}
public Object current() {
return items[i];
}
public void next() {
if (i < items.length)
i++;
}
}
public Selector selector() {
return new SequenceSelector();
}
public static void main(String[] args) {
try {
Main sequence = new Main(10);
for (int i = 0; i < 11; i++) {
sequence.add(i);
}