This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

catch exceptions in method overriding  RSS feed

 
kesava chaitanya
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i want to understand how these exceptions raise in method overriding?

i have written one super class like this

package example;
import java.io.*;
import java.sql.*;
public class Super
{
void eat() throws SQLException
{
System.out.println("in super eat");
}

public void eat(String x)
{
System.out.println("in super eat String argument=="+x);
}

}

i have written one sub class . i have intentionally written wrong SQL query so that SQL Exception should occur ;
i have overriden eat() method in the sub class,in the SQLException block I rethow the SQLException;
why should i write following block in the Sub class;Because only to catch the sqlexception;


try
{
sub.eat();
}catch(SQLException sql)
{
System.out.println("in sub ctach block...");
}


Is it neccassary to throw the SQLException in the base class eat() method ;

package example;
import java.sql.*;
import java.io.*;

public class Sub extends Super
{
protected void eat() throws SQLException
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc racle:thin:@172.16.31.12:1521:egl","egl1005","egl");
Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery("SELECTtt ADDRESSLINE1, ADDRESSLINE2, ADDRESSLINE3, CITY, STATE, ZIPCODE, PHONENO, FAX, COUNTRYID FROM FS_ADDRESS WHERE ADDRESSID= 400052424");
while(rs.next())
{
System.out.println(rs.getString(1));
}
System.out.println(con);
}catch(ClassNotFoundException cnf)
{
System.out.println("in catch block");
}
catch(SQLException sql)
{

throw sql;

}
}


public static void main(String[] args)
{
Super sub = new Sub();
try
{
sub.eat();
}catch(SQLException sql)
{
System.out.println("in sub ctach block...");
}

sub.eat("gg");
}
}
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kesava chaitanya:
Is it neccassary to throw the SQLException in the base class eat() method[?]
Any method that throws a checked exception like SQLException must declare it in its throws clause. Since the superclass method throws Exception, you can specify "throws Exception" in your subclass or just "throws SQLException." You may narrow the set of exceptions thrown when overriding a method but not expand it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!