Why do I need to catch this exception?
Hello all
This is a question about exception handling. I have to build a diary application that lets you save reminders on particular dates using xml. Just to make it a little tougher, I was not allowed to use the Calendar class. This is the code I wrote:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
importstatic java.lang.Math.*;
publicclass CalendarAssignmentextends JFrameimplements ActionListener
{
int MonthLength [] ={ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public JButton [] days =new JButton[43];
private JLabel lbl, reminderlbl;
private JPanel top, grid, remindercenter, reminderbottom;
private JFrame reminderframe;
private JTextField year1, reminderinput, dayno;
private JComboBox months;
private Container container;
private JButton fetch, save, cancel;
private Document doc;
private File file;
private Node node;
private String year, month, day;
publicstaticvoid main( String[] args ){
CalendarAssignment c =new CalendarAssignment( );
c.setSize( 400, 300 );
c.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
c.show( );
}
public CalendarAssignment( ){
int CurrentYear, CurrentMonth;
String YearString, MonthString, Now;
Date today;
container = getContentPane( );
container.setLayout(new BorderLayout( ) );
SimpleDateFormat DateFormatter;
DateFormatter =new SimpleDateFormat("MM.yyyy" );
today =new Date( );
Now = DateFormatter.format( today );
MonthString = Now.substring( 0,2 );
YearString = Now.substring( 3,7 );
CurrentMonth = Integer.valueOf( MonthString );
CurrentYear = Integer.valueOf( YearString );
top =new JPanel( );
String [] items ={"January","February","March","April","May","June",
"July","August","September","October","November",
"December"};
months =new JComboBox( items );
months.setEditable(false );
months.setSelectedIndex( CurrentMonth - 1 );
year1 =new JTextField( );
year1.setText( YearString );
year1.setEditable(true );
year1.setHorizontalAlignment( year1.CENTER );
fetch =new JButton("Fetch Month" );
fetch.addActionListener(this );
top.setLayout(new GridLayout( 1, 3, 20, 0 ) );
top.add( months );
top.add( year1 );
top.add( fetch );
grid =new JPanel( );
grid.setLayout(new GridLayout( 7, 7, 0, 0 ) );
String [] week ={"Mon","Tue","Wed","Thur","Fri","Sat","Sun"};
for (int a = 0; a < 7; a ++ ){
JLabel lbl =new JLabel( week[a], JLabel.CENTER );
grid.add( lbl );
}
for (int i = 0; i < 42; i ++ ){
days[i] =new JButton( );
grid.add( days[i] );
days[i].addActionListener(this );
}
DrawCalendar( CurrentMonth, CurrentYear );
container.add( top, BorderLayout.NORTH );
container.add( grid, BorderLayout.CENTER );
}
privatevoid DrawCalendar(int SelectMonth,int SelectYear ){
int DisplayMonthLength, Buttons;
String ButtonID ="";
int OffSet = MonthStart( SelectMonth, SelectYear );
DisplayMonthLength = MonthLength [SelectMonth - 1];
if ( SelectMonth == 2 )
DisplayMonthLength += LeapYear( SelectYear );
for ( Buttons = 1; Buttons < 43; Buttons ++ ){
if ( ( Buttons <= OffSet ) || ( Buttons > ( DisplayMonthLength + OffSet ) ) ){
ButtonID ="";
days[Buttons-1].setEnabled(false );
}
else{
ButtonID = Integer.toString( Buttons - OffSet );
days[Buttons-1].setEnabled(true );
}
days[Buttons-1].setLabel( ButtonID );
grid.add( days[Buttons-1] );
}
}
privateint LeapYear(int year ){
int FourHundred, OneHundred, Fourth;
FourHundred = year % 400;
OneHundred = year % 100;
Fourth = year % 4;
if( ( ( FourHundred == 0 ) ) || ( ( OneHundred != 0 ) && ( Fourth == 0 ) ) )
return ( 1 );
else
return ( 0 );
}
privateint MonthStart(int Month,int Year ){
int OffSet, LastMonths, BeforeOrAfter, Years;
int AllDays = 0;
int YearDays = 365;
int YearMonths = 12;
BeforeOrAfter = Year - 2006;
Years = abs( BeforeOrAfter );
if( BeforeOrAfter != 0 )
BeforeOrAfter = BeforeOrAfter / Years;
switch( BeforeOrAfter ){
case 1:
for(int a = 2006; a < Year; a ++ ){
AllDays += YearDays + LeapYear( a );
}
AllDays += LastMonthsCalc( Month, Year );
break;
case -1:
for(int a = 2005; a > Year; a -- ){
AllDays += YearDays + LeapYear( a );
}
for( LastMonths = YearMonths; LastMonths >= Month; LastMonths -- ){
AllDays += MonthLength[LastMonths - 1];
if( LastMonths == 2 )
AllDays += LeapYear( Year );
}
break;
default:
if( Month > 1 )
AllDays += ( LastMonthsCalc( Month, Year ) );
}
OffSet = AllDays % 7;
if( BeforeOrAfter ==( -1 ) )
return( 6 - OffSet );
elseif( OffSet > 0 )
return( OffSet - 1 );
else
return( 6 );
}
privateint LastMonthsCalc(int Month,int Year ){
int Counter;
int days = 0;
for( Counter = 1; Counter < Month; Counter ++ ){
days += MonthLength[Counter - 1];
if( Counter == 2 )
days += LeapYear( Year );
}
return( days );
}
publicvoid CreateReminder( String buttonID, String yearID, String monthID ){
reminderframe =new JFrame( );
reminderlbl =new JLabel( );
reminderframe.setLayout(new GridLayout( 2, 1, 0, 0 ) );
remindercenter =new JPanel( );
reminderlbl =new JLabel("Please type in reminder to be saved for " + buttonID +" " + monthID +" " + yearID +":", JLabel.CENTER );
reminderinput =new JTextField( 30 );
reminderinput.setHorizontalAlignment( reminderinput.CENTER );
reminderinput.setEditable(true );
remindercenter.setLayout(new GridLayout( 2, 1, 0, 0 ) );
remindercenter.add( reminderlbl );
remindercenter.add( reminderinput );
reminderbottom =new JPanel( );
save =new JButton("Save" );
save.addActionListener(this );
cancel =new JButton("Cancel" );
cancel.addActionListener(this );
dayno =new JTextField( buttonID );
dayno.setEditable(false );
dayno.setEnabled(false );
dayno.show(false );
reminderbottom.setLayout(new FlowLayout( ) );
reminderbottom.add( save );
reminderbottom.add( cancel );
reminderbottom.add( dayno );
reminderframe.setSize( 500, 75 );
reminderframe.add( remindercenter );
reminderframe.add( reminderbottom );
reminderframe.pack( );
reminderframe.show( );
}
publicvoid SaveReminder( String dayID, String yearID, String monthID )throws Exception{
file =new File("Diary.xml" );
doc = DocumentBuilderFactory.newInstance( ).newDocumentBuilder( ).parse( file.toURL( ).toString( ) );
String year = yearID;
String month = monthID;
String day = dayID;
//System.out.println( year );
//System.out.println( month );
//System.out.println( day );
CreateEntry( doc.getDocumentElement( ) );
writeXmlFile( );
}
publicboolean CreateEntry( Node node ){
Node searchNode;
searchNode = getYear( node );
if( searchNode ==null ){
Element newNode = doc.createElement("Year" );
searchNode = node.appendChild( newNode );
newNode.setAttribute("Id", year );
}
node = searchNode;
searchNode = getMonth( node );
if( searchNode ==null ){
Element newNode = doc.createElement("Month" );
searchNode = node.appendChild( newNode );
newNode.setAttribute("Id", month );
}
node = searchNode;
searchNode = getDay( node );
if( searchNode ==null ){
Element newNode = doc.createElement("Day" );
searchNode = node.appendChild( newNode );
newNode.setAttribute("Id", day );
}
node = searchNode;
String entry = reminderinput.getText( );
Node textNode = doc.createTextNode( entry );
node.appendChild( textNode );
returntrue;
}
private Node getYear( Node node ){
node = node.getFirstChild( );
while( node !=null ){
if(node.getNodeName( ).equals("Year" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == year )
return node;
node = node.getNextSibling( );
}
returnnull;
}
private Node getMonth( Node node ){
node = node.getFirstChild( );
while( node !=null ){
if( node.getNodeName( ).equals("Month" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == month )
return node;
node = node.getNextSibling( );
}
returnnull;
}
private Node getDay( Node node ){
node = node.getFirstChild( );
while( node !=null ){
if( node.getNodeName( ).equals("Day" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == day )
return node;
node = node.getNextSibling( );
}
returnnull;
}
privatevoid writeXmlFile( )throws Exception{
Source source =new DOMSource( doc );
Result result =new StreamResult( file );
Transformer xformer = TransformerFactory.newInstance( ).newTransformer( );
xformer.setOutputProperty( OutputKeys.INDENT,"yes" );
xformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd" );
xformer.transform( source, result );
}
publicvoid actionPerformed( ActionEvent e ){
String IDButton = e.getActionCommand( );
String IDYear = year1.getText( );
Object IDMonthObj = months.getSelectedItem( );
if( e.getSource( ) == fetch ){
String YearText = year1.getText( );
int YearNumber = Integer.valueOf( YearText );
int MonthsIndex = months.getSelectedIndex( ) + 1;
DrawCalendar( MonthsIndex, YearNumber );
}
elseif( e.getSource( ) == cancel ){
reminderframe.hide( );
}
elseif( e.getSource( ) == save ){
String IDDay = dayno.getText( );
String IDMonth = String.valueOf( IDMonthObj );
SaveReminder( IDDay, IDYear, IDMonth );
}
else{
String IDMonth = String.valueOf( IDMonthObj );
Toolkit.getDefaultToolkit( ).beep( );
int n = JOptionPane.showConfirmDialog( null,"Set reminder on this date?","Question", JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION ){
CreateReminder( IDButton, IDYear, IDMonth );
}
}
}
}
If you compile it, you will realise that I get an error about exception handling. My lecturer gave me an example code of how to do the same thing without using a GUI:
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
publicclass CallDOM
{
Document doc;
File file;
Scanner input;
int year, month, day;
String currentYear, currentMonth;
publicstaticvoid main(String args[])throws Exception
{
CallDOM cd=new CallDOM();
}
CallDOM()throws Exception
{
file=new File("Diary.xml");
//create DOM from file
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file.toURL().toString());
input=new Scanner(System.in);
System.out.println("1) Create entry");
System.out.println("2) Read entry");
System.out.println("3) Show Diary");
System.out.println("4) Quit");
int choice=input.nextInt();
while(choice!=4)
{
switch(choice)
{
case 1: GetDate();CreateEntry(doc.getDocumentElement());break;
case 2: GetDate();ReadEntry(doc.getDocumentElement());break;
case 3: ShowDiary(doc.getDocumentElement());
}
System.out.println("1) Create entry");
System.out.println("2) Read entry");
System.out.println("3) Show Diary");
System.out.println("4) Quit");
choice=input.nextInt();
}
writeXmlFile();
}
publicvoid GetDate()
{
System.out.println("Enter date (dd mm yyyy)");
day=input.nextInt();
month=input.nextInt();
year=input.nextInt();
}
publicboolean ReadEntry(Node node)
{
node = getYear(node);
if(node==null)returnfalse;
node = getMonth(node);
if(node==null)returnfalse;
node = getDay(node);
if(node==null)returnfalse;
node = node.getFirstChild();
while(node!=null)
{
System.out.println(node.getNodeValue().trim());
node=node.getNextSibling();
}
returntrue;
}
publicboolean CreateEntry(Node node)
{
Node searchNode;
searchNode = getYear(node);
if(searchNode==null)
{
Element newNode = doc.createElement("Year");
searchNode = node.appendChild(newNode);
newNode.setAttribute("Id",Integer.toString(year));
}
node = searchNode;
searchNode = getMonth(node);
if(searchNode==null)
{
Element newNode = doc.createElement("Month");
searchNode = node.appendChild(newNode);
newNode.setAttribute("Id",Integer.toString(month));
}
node = searchNode;
searchNode = getDay(node);
if(searchNode==null)
{
Element newNode = doc.createElement("Day");
searchNode = node.appendChild(newNode);
newNode.setAttribute("Id",Integer.toString(day));
}
node = searchNode;
System.out.println("Enter Text");
String entry=input.next();
entry+=input.nextLine();
Node textNode = doc.createTextNode(entry);
node.appendChild(textNode);
returntrue;
}
publicvoid ShowDiary(Node node)
{
Stack<Node> stack=new Stack<Node>();
Node child;
stack.push(node);
while(!stack.empty())
{
node = stack.pop();
if(ProcessNode(node))
{
child = node.getLastChild();
while(child!=null)
{
stack.push(child);
child = child.getPreviousSibling();
}
}
}
}
privateboolean ProcessNode(Node node)
{
if(node.getNodeName().equals("Year"))
currentYear=node.getAttributes().item(0).getNodeValue();
if(node.getNodeName().equals("Month"))
currentMonth=node.getAttributes().item(0).getNodeValue();
if(node.getNodeName().equals("Day"))
{
System.out.print(node.getAttributes().item(0).getNodeValue()+"/"+
currentMonth+"/"+currentYear+": ");
node=node.getFirstChild();
while(node!=null)
{
System.out.println(node.getNodeValue().trim());
node=node.getNextSibling();
}
returnfalse;
}
returntrue;
}
private Node getYear(Node node)
{
node=node.getFirstChild();
while(node!=null)
{
if(node.getNodeName().equals("Year")
&& Integer.valueOf(node.getAttributes().item(0).getNodeValue())==year)
return node;
node = node.getNextSibling();
}
returnnull;
}
private Node getMonth(Node node)
{
node=node.getFirstChild();
while(node!=null)
{
if(node.getNodeName().equals("Month")
&& Integer.valueOf(node.getAttributes().item(0).getNodeValue())==month)
return node;
node = node.getNextSibling();
}
returnnull;
}
private Node getDay(Node node)
{
node=node.getFirstChild();
while(node!=null)
{
if(node.getNodeName().equals("Day")
&& Integer.valueOf(node.getAttributes().item(0).getNodeValue())==day)
return node;
node = node.getNextSibling();
}
returnnull;
}
privatevoid writeXmlFile()throws Exception
{
Source source =new DOMSource(doc);
Result result =new StreamResult(file);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT,"yes");
xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd");
xformer.transform(source, result);
}
}
My question is, why does the exceptions in the example code not need to be caught? And why do I have to catch the exceptions in my code? Several exceptions are thrown in the example code, but there is no catch statement.
Thanks for any advice!!

