Java Exceptions

public class DivideByZeroException extends ArithmeticException{

public DivideByZeroException(){

super(“Attempted to divide by zero”);

}

public DivideByZeroException(String message){

super(message);

}

}

import java.text.DecimalFormat;

import java.swing.*;

import java.awt.*;

import java.awt.event.*;

public class DivideByZeroTest extends Jframe implements ActionListener{

private JtextField i1,i2,o1;

private int num1,num2;

private double result;

public DivideByZeroTest(){

super(“Demonstrating exceptions”);

Container c = getContentPane();

c.setLayout(new GridLayout(3,2));

c.add(new JLabel(“Enter Numerator”,SwingConstants.RIGHT));

i1 = new JtextField(10);

c.add(i1);

c.add(new JLabel(“Enter Denominator an press Enter”,SwingConstants.RIGHT));

i2 = new JtextField(10);

c.add(i2);

i2.addActionListener(

}

public class UsingExceptions{

public static void main(String args[]){

try{

method1();

}

catch(Exception e){

System.out.println(e.getMessage()+ “\n”);

e.printStackTrace();

}

}

public static void method1() throws Exception{

method2();

}

public static void method2() throws Exception{

method3();

}

public static void method3() throws Exception{

throw new Exception(“Exception thrown in method 3”);

}

}

OUTPUT STACK TRACE

Exception thrown in method3

java.lang.Exception: Exception thrown in method3

at UsingException.method3(UsingException.java:28)

at UsingException.method2(UsingException.java:23)

at UsingException.method1(UsingException.java:18)

at UsingException.main(UsingException.java:8)

No comments: