Exceptions On File I/O Interface Methods

Apr 24, 2014

I'm wondering about the use of exceptions to handle errors that might occur during file I/O when the I/O is done by a method implementing an interface's method. The idea is for the interface to provide a uniform way for application code to read (and write, though I'm not addressing that in this post) a document from a file, given a File object that specifies the on-disk location of the document. The "document" can be an instance of any class the application programmer wants it to be, provided that it can be created from a file stored on disk. Here's the interface definition:

public interface DocumentRamrod<T>
{
public T openDocumentFile(File file) throws FileNotFoundException;
}

A simple implementation, when T is a class that just holds a String, might look like this (Please overlook the fact that there is no call to the BufferedReader's close method, as it's not needed for this example.):

public class MyRamrod implements DocumentRamrod<OneLineOfText>
{
public OneLineOfText openDocumentFile(File file) throws FileNotFoundException
{
return new OneLineOfText(new BufferedReader(new FileReader(file)).readLine());
}
}

But, that one line where the file is read (Line 5) might generate an IOException.To cope with it, I could add a try-catch to the implementation like this:

public class MyRamrod implements DocumentRamrod<OneLineOfText>
{
public OneLineOfText openDocumentFile(File file) throws FileNotFoundException
{
try
{
return new OneLineOfText(new BufferedReader(new FileReader(file)).readLine());
} catch (IOException ex)
{
Logger.getLogger(MyRamrod.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Or, I could add that to the list of exceptions defined for the method in the interface, like this:

public interface DocumentRamrod<T>
{
public T openDocumentFile(File file) throws FileNotFoundException, IOException
}

But that's where I'm getting nervous, as it makes me realize that, with an infinite number of possible implementations of openDocumentFile, I can't predict what all the exceptions thrown might be.should I have openDocumentFile simply throw Exception, and let the application programmer sort out which one(s) might actually be thrown, should I keep listing them as it become clear which ones are likely to be thrown, or should I not have openDocumentFile throw any exceptions and let the application programmer deal with it in the implementation of openDocumentFile (with try-catch blocks, etc.)? In Good Old C, I'd have passed back a null to indicate some general failure, with the various callers up the call-stack having to either deal with it or pass that back themselves (until some routine up the stack finally did deal with it), but that seems like an approach the whole exception mechanism was designed to avoid.

I'm thinking the right choice is to have openDocumentFile throw Exception, and let the application programmers decide which subclasses of Exception they really want to deal with. But I have learned to be humble about the things I think, where Java is concerned,

View Replies


ADVERTISEMENT

Using Methods Of Interface

Feb 5, 2014

I have following code. In this code CSClient is an interface. All methods of CSClient are implementaed in CSClientImpl class. Do I not need CS Client Impl imported in this code ?

How can I call getBranch() of CSClient, which is not implemented in CSClient as " this. getCsClient(). get Branch (new CSVPath(vpath), true);" ? This code works fine without any error in eclipse.

How can a method getBranch(), which is implemented in CSClientImpl class be used in this code without importing CSClientImpl ?

package com.rbc.teamsite.client;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

[code]....

View Replies View Related

Calling Methods From Interface

Jul 26, 2014

I'm working with Libgdx but I have a basic java question. I'm trying to access the overridden methods from and interface in another class via a call but I'm not sure how. This is what I've got so far :

Java Code:

public interface Controller {
public void show ();
}
public class MainActivity extends AndroidApplication implements Controller {
@Override
public void showAd(boolean show) {
System.out.println("TEST");

[Code] ....

Right now this code returns a null pointer at the call.

View Replies View Related

Why Interface Inherit All Non Final Methods From Object Class

Jan 8, 2014

why interfaces inherit prototype of all the non final methods of the object class in itself? Object class is parent class of all the class and Interface is not the class.

View Replies View Related

Additional Methods From Specific Classes That Implement Interface

Jan 8, 2014

I am writing a game in Java for Android (although my question isn't Android or Game Dev specific).

I have a SceneManager class and a Scene interface and then various other classes that implement the Scene interface (Code at the end of this post).

Basically, in my MainGame class (which also implements the Scene Interface for Touch Event capturing purposes) I hold the bulk of my game code. Methods in this class are then called from my Level classes. (most of these are needed in all levels so it makes sense to hold them here and call them from the levels to eliminate unnecessary code duplication)

So, I have Level1, Level2......... Level20 classes which all implement Scene.

Now, the problem comes because in only 2 of my Levels something can happen (that can't in the other 18) and I need to run a response method in these 2 levels (the method isn't exactly the same, the response to this event happening is different for both levels).

To run common methods from my classes, I use my Scene Manager like this:

SceneManager.getInstance().getCurrentScene().updateLogic();
SceneManager.getInstance().getCurrentScene().render();

(The above is from my gameloop) - So it will run the updateLogic(); and render(); methods from whichever is the current scene (Level).

Scene is changed like so:

SceneManager.getInstance().setCurrentScene(LevelX);

This works great as all Level's have an updateLogic(); and render(); method.

So from my mainGame class, I am doing something like : (pseudo code)

public void checkIfSomethingHappened(){
if (something happens){
if (currentLevel==5){
Level5.response();}

[Code]....

The above would be called from my 2 level classes. So something like:

MainGame.checkIfSomethingHappened(); //Called in addition to the normal methods that make up that level

I don't really want to have this (second) 'if' statement here in the middle of my performance critical game loop.

What I'm after is something like this:

if (something happens){
SceneManager.getInstance().getCurrentScene().response();
}

However, this would require me to put stubs in the other 18 classes.

I'm thinking there must be a way to do this as the SceneManager already knows the current scene so it seems a waste checking it again via an if (or switch) statement. What is the best way to do this without having to put stubs into classes that don't require this method?

View Replies View Related

Using Interface To Process A File And Return In Different Format

Jun 15, 2014

I'm working on an assignment where the program has to process a file and read every line then print it out in all caps. I'm pretty sure I have most of it written out, however, I am having trouble with my main method. I am supposed to call my go method in my FileProcessor class and have it use the StringProcessor interface to call my Upper class. I'm using an interface because I will be adding other classes later, but for now I am having trouble with implementing it all in my Driver class.

How do I declare a StringProcessor object in my Driver class and how can I use it so that it would create the file in all caps?

Here's my code so far:

Driver.java
import java.util.Scanner;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;
import java.io.File;

[Code].....

View Replies View Related

How To Throw Exceptions

Nov 22, 2014

I am just learning how to throw exceptions, and I'm stuck on the last part,

Here is where I created the exception that receives a string consisting of ID and wage.

public class EmployeeException extends Exception
{
public EmployeeException(String Employee)
{
super(Employee);
}
}

Here is where I created the Employee class with the two fields. I also believe I am throwing the exception if the hourly wage is < $6 or > $50.

public class Employee
{
int idNum;
double hourlyWage; 
public void Employee(int empID, double empWage) throws EmployeeException
{
idNum = empID;
hourlyWage = empWage;

[Code]...

Now, I need to write an application with three employees and display a message when an employee is successfully created or not. This is what I have so far... I'm trying to get it to work with one employee, and then I can easily go back and add two more.

import javax.swing.*;
public class ThrowEmployee
{
public static void main (String[] args)
{
try
{
Employee one = new Employee(542, 15.20);
}
 
[Code

The current compile error that I'm receiving is: ThrowEmployee.java:12: error: constructor Employee in class Employee cannot be applied to given types;

Employee one = new Employee(542, 15.20);
^
required: no arguments
found: int,double
reason: actual and formal argument lists differ in length
1 error

I have public void Employee(int empID, double empWage) in my Employee class, so why is it saying that no arguments are required? Not sure if I'm missing a step with throwing exceptions, because this error has always been a simple fix when I've come across it in the past?!?

View Replies View Related

EJB / EE :: JPA Exceptions - How To Handle

Apr 14, 2014

In my EJB modules, to prevent that any JPA exception is ever thrown, I check the condition that would cause the exception beforehand. For example, the exception javax.​persistence.EntityExistsException is never thrown because, before persisting the entity, I check if such primary key already exists in the DB. Is it the right way to do this?

Another approach is too allow the JPA exceptions to be thrown and catch them in a try-catch block, and then throw my custom exception from the "catch" block. However it requires to call EntityManager.flush () at the end of the "try" block. Otherwise the exception throw could be deferred and never be caught by my block.

View Replies View Related

Reading A File And Methods

Mar 18, 2015

package project3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
 
[code]....

method countMail!! Also the text file you are reading from is attached as ampo_uumail.txt and i also have a picture of the output.

View Replies View Related

How Many Exceptions Should A Method Throw At Most

Jul 31, 2014

There are times that my methods need to report the caller about many kinds of errors, represented as checked exceptions. This makes my methods look like very convoluted. It happens mostly when I work with stateless EJBs and databases. Sometimes I end throwing even 8 different exceptions! Are they too many?

Many of them inherit from common exceptions, so I've been tempted to throw the parent classes. But I've quickly discarded that option because I've read that it's a bad practice, since a method may throw only a subset of the children of that parent class, not all.

Finally, I've studied these possibilities:

1. Throwing the parent class (mentioned above).
2. Throwing a common exception with an error ID or code as message.
3. Throwing a common exception with an enum as member, as if it were an ID or code (safer than the #2).

All them show the same defect that the #1. However it's more a conceptual problem than a technical one, because my callers always use the same mechanism to treat every "specialization" of the same exception, without worrying about if the method really can return it or not.

View Replies View Related

Test That A Function Has No Any Exceptions

Aug 3, 2014

I want to test that a function has no any exceptions.In C++ and Google Test Framework (GTest) it will look like this:

ASSERT_NO_THROW({
actual = divide(a, b);
});

How will it look in Java?

View Replies View Related

Exceptions For Multiple Inputs

Oct 29, 2014

I'm writing a program that accepts three doubles from the user, and performs calculations on them. I want to be able to handle input mismatch exceptions on each individually (i.e., if the user enters a double for the first, then a letter for the second, I'd like to be able to keep the value entered for the first, and only require that the user try again with the second, then the third, etc.)... I tried putting each input instance into its own try/catch blocks, but it always goes back to #1 when an invalid input is entered. Right now, I have all three in one try/catch:

Java Code:

package com.itse2317;
import java.util.Scanner;
import java.util.InputMismatchException;
class Triangle
{
public static double side1 = 0.0, side2 = 0.0, side3 = 0.0;

[code]...

View Replies View Related

Use TextIO Methods To Read File

Dec 2, 2014

For the unit 3 assignment, you must develop a program. that reads the file icecream.dat. This file is supplied in the Files for Unit 3 Assignment directory in Unit 3. You must use TextIO methods to read the file. As you read the file, count the total number of ice cream cones that were sold. (This is the same as the number of lines that you read from the file.) Also count the total number of "Strawberry" cones that were sold.

At the end of the program, print out the total number of cones, the number of Strawberry cones, and the percentage of cones that were Strawberry.To do this program, you have to know when to stop reading from the file. TextIO has a function named TextIO.eof() to check whether the entire file has been read. The value of this function is true if the entire file has been read. The value is false if there is more data in the file. You want to continue reading from the file as long as TextIO.eof() is false.

Note: Suppose that flavor is a variable of type String and you want to test whether its value is "Strawberry". To do this, test whether flavor.equals("Strawberry"). (Do not use == to test for equality of Strings.)

Each line of the file icecream.dat is an ice cream flavor such as "Vanilla" or "Strawberry." A line represents the sale of one ice cream cone of the given flavor.

You must complete your program, test, debug, and execute it. You must submit your java code file. The output of your program must be captured by either copying the content in the output window and pasting it into a text document that you submit along with your java code file, or by capturing the image of the screen which contains the output of your java program. In windows you can capture a screen shot with the Ctrl Alt and Print Screen key sequence. This image can then be pasted into a Word, WordPad, or OpenOffice document which can be submitted with your assignment.

For students using the programr service online. Make sure that you create both the TextIO.java and the icecream.dat files as java project files. I found it was easier to rename icecream.dat to icecream.txt for some reason. For students using Netbeans, use the same set of rules that were defined in Unit 2 to setup your project and incude the TextIO.java file as we did in unit 2. Also make sure that you copy the icecream.dat file into your project directory so that it can be found by your java program.

View Replies View Related

Override Certain Methods In Class File?

Oct 16, 2014

I am wanting to override certain methods in some Minecraft class files, and tell those class files to use code from my class files.

And no, I don't mean extend a class. When I try to extend from the main Block.Class, it makes that file as another block file for the game, or something.

So like, I want to tell the main file that handles block registries to use the code from my class file to register my custom blocks to the list of blocks, but without modifying that main block file.

Is this even something that's possible?

Also, I know that the way a file is named affects the loading order. My class files would be named using symbols to make it load right before the class file I want to override.

View Replies View Related

Grasping Concept Of Throwing Own Exceptions

Dec 3, 2014

I am having some difficulties grasping the concept of throwing your own exceptions. How do I get this to repeatedly ask the user to enter a valid value for hours. Also i am having difficulties in the method with using the throw new InvalidHrExcep("That value is invalid"); i cannot get this to work.

public class exceptionProgram {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws InvalidHrExcep
{
int day=0;
int month = 0;
int year=0;
int hours=0;
int minutes=0;
int seconds=0;

[code]...

View Replies View Related

Final Field Initialization With Exceptions

May 11, 2014

consider:
 
class A {
     final Object b;
     public A(C c) {
          try {
               b = c.someMethodThatMayThrowSomeException();
          } catch (SomeException e) {
               b = null; // This line results in compiler error: "variable b might already have been assigned"
          }
     } // take away b=null line and you get "variable b might not have been initialized" on this line
}
 
Why? How could 'b' be assigned if the exception was thrown?
 
Btw, the workaround is to wrap the method call:
 
private final Object initB() {
     try {
          return c.someMethodThatMayThrowSomeException();
     } catch (SomeException e) {
          return null;
     }
}
 
and use b = initB(); in the constructor.  But that seems like it should be unnecessary.

View Replies View Related

JAMON Spring Unable To Monitor Exceptions

Jul 12, 2014

I am currently working on integrating JAMON version 2.76 in our existing application

following are details of environment
JDK 1.5
Server weblogic 9.2
OS windows
Spring version 2.5

first we have added following entry for jamon monitor

<bean id="jamonPerformanceMonitor" class="org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptor">
<property name="useDynamicLogger" value="false"/>
<property name="trackAllInvocations" value="true"/>
</bean>

then added this interceptor as preinterceptor in existing

<bean id="applicationBO" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>

[Code].....

currently we can able to monitor all calls given to this class but whenever any exception thrown in this class hierarchy we are not able to track it on exceptions.jsp of JAMON

View Replies View Related

Null Pointer Exceptions On First Attempt At JButtons

Dec 12, 2014

I am designing/coding a blackjack GUI program and I'm trying to add function to my JButtons. Problem is, I now have 2 NullPointerExceptions.

public class GameConsole {
Player user;
Player dealer;
Deck playingDeck;
ValidateInput validate = new ValidateInput();

[Code] .....

I am trying to do. I am getting the following exception/stack trace at line 14 in userTurn()

Exception in thread "main" java.lang.NullPointerException
at blackjackControls.GameConsole.userTurn(GameConsole.java:163)
at blackjackControls.GameConsole.gamePlay(GameConsole.java:87)
at blackjackControls.Main.main(Main.java:7)

and then the program continues and after I click the button I get :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at blackjackControls.GameConsole.userTurn(GameConsole.java:163)
at blackjackControls.ResultPanel$1.actionPerformed(ResultPanel.java:34)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
//and then about 30 more "at" lines

Why am I getting these exceptions and how do I fix it?

View Replies View Related

Java Program Using Apache POI Giving Exceptions

May 13, 2015

I am having some serious difficulty getting my project off the ground. I have the following code:

FileInputStream file = new FileInputStream(new File("src/retestchecker/test_sheet.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell x = row.getCell(3);
System.out.println(x);

Everything is properly imported, etc etc.. But I am getting this error and I am not sure what it means:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
at retestchecker.RetestChecker.main(RetestChecker.java:23)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)

[Code] .....

Java Result: 1

I am using Netbeans and the latest version of Apache POI that was released May 11, 2015.

The line 23 that the error refers to is this line:

XSSFWorkbook workbook = new XSSFWorkbook(file);

View Replies View Related

Two Classes Compile Without Errors But When Try To Run They Throw Exceptions

Jan 24, 2015

numHitslocs

public class simpleDotCom {
int numHits=0;
int[] locationCells;
public void setlocationCells(int[] locs){
locs=locationCells;

[Code] ....

View Replies View Related

Encounter Exceptions While Dispatch Aglet To Different Host

Apr 20, 2015

I encounter exceptions while dispatch an aglet to different hostit moves only in two url and stop the execution.

My code (ControllerChild.java and ControllerExample.java).

// ControllerChild.java
package controllerexample;
import com.ibm.aglet.*;
import com.ibm.aglet.event.*;
import java.net.*;
public class ControllerChild extends Aglet {
URL url;
AgletID aid;

[code]....

View Replies View Related

EJB / EE :: Design Patterns - Usage Of Transactions And Exceptions

Feb 3, 2015

When it comes to Java EE I see many developers having trouble with the usage of transactions and exceptions and when to use what.

I see a full chapter of RESTful Web Services, but do you also relate these Web Services to their counterparts (SOAP Web Services)?

View Replies View Related

Web Services :: How To Invoke Methods Using Stand Alone File No Eclipse

Apr 17, 2015

I am trying web service first time so want to client application which will consume webservice which are hosted online for testing purpose

now i want to call some methods defined in this wsdl [URL]....

can anyone tell how should i invoke methods using stand alone java file no eclipse which jar files should i use ?

View Replies View Related

JavaFX 2.0 :: Other Methods To Load CSS File From MySQL DB Table

Jan 29, 2015

I am trying to load a CSS file from a mySql DB  table (each row represent a customer that use the application, and each one can set  his own CSS file).

How can I convert the Stream / String that I loaded from the Clob column to something that I can use here XXXX

scene().getStylesheets().add( XXXX );
  
I found alot of examples, but they all talking about files from filesystem, or URLs. My CSS file is in the application memory. I want to prevent the option to write my string as a new file and then read it again. I have no problem with loading the CSS file from database, this part is O.K.

View Replies View Related

Points To Ponder For Java Null Pointer Exceptions

Dec 12, 2014

This is what I wrote and I get this eror : Points to Ponder for Java Null Pointer Exceptions

public class Line{ 
private Punkt2d pStart;
private Punkt2d pEnde;
public Line(Punkt2d pStart, Punkt2d pEnde) {
this.pStart = pStart;
this.pEnde= pEnde;

[Code] ....

Erorr:

Exception in thread "main" java.lang.NullPointerException
at Line.getLength(Line.java:38)
at Aufgabe_6_1.main(Aufgabe_6_1.java:7)

View Replies View Related

JavaFX 2.0 :: How To Recover From Too Many Touch Points Reported Exceptions

Sep 17, 2014

I'm trying to stress test JavaFX and I'm on Window 8.1 using 1.8.0_20-b26. I have an application that has many objects on the scene with animation timers and overall it purposefully runs very slow. I have listeners on the root AnchorPane for touch input and if I generate many touch point events after a few minutes I get "Too many touch points reported" exceptions (posted below) and the app of course no longer responds to touch input. Is it possible to catch the exception and then reset the scene touch input so it goes back to normal without restarting the application? If it lost any current touch input that's fine.
 
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: Too many touch points reported
  at javafx.scene.Scene$ScenePeerListener.touchEventNext(Scene.java:2686)
  at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleNextTouchEvent$346(GlassViewEventHandler.java:1090)

[Code]....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved