Can anyone tell me where I'm going wrong in my program to get this error? I've put an "*" next to the lines which give me this error. Using Eclipse btw. The whole code is linked below. Thanks!!
public static void main(String[] args)
{
openFile();
addRecords();
closeFile();
}
public static void openFile()
{
try
*{
* output = new Formatter("numbers.txt");
*}
*catch
{
System.err.println("Write permission denied. Terminating.");
System.exit(1);
}
*catch
{
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
http://pastebin.com/CKPQzCNi
Your catch clause is an exception handler which takes in an argument. The argument type, ExceptionType must be declared and must be the name of a class that inherits from the Throwable class. I see your try-catch block is not specifying an argument to either of the catch clauses.
Refer to the method addRecords() in the code you have referenced on pastebin for an example of correct exception handling.
Related
This question already has answers here:
What are checked exceptions in Java/C#?
(3 answers)
Closed 4 years ago.
The constructor Formatter(String fileName) doesn't seem to compile when I don't handle FileNotFoundException even if the file already exists.
Here's the code that works:
import java.util.*;
public class CreatingFiles {
public static void main(String[] args) {
final Formatter MYFILE;
try {
MYFILE = new Formatter("john.txt");
System.out.println("File created");
}
catch (Exception e) {
System.out.println("Error!");
}
}
}
However when I remove the try/catch block:
import java.util.*;
public class CreatingFiles {
public static void main(String[] args) {
final Formatter MYFILE;
MYFILE = new Formatter("john.txt");
}
}
The compiler tells me that I have to either throw or catch the exception. So why doesn't it work without handling the exception?
The constructor Formatter(String) [https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)], throws a FileNotFound exception [https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html], a checked exception [https://en.wikibooks.org/wiki/Java_Programming/Checked_Exceptions], so you have to catch it or re-throw it.
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)
SecurityException - If a security manager is present and checkWrite(fileName) denies write access to the file
FileNotFoundException - If the given file name does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
Compiler don't know if the file exist. It will find only at execution.
You can put throws ExceptionName in method declaration
public void MyMethod() throws ExceptionName{
//TODO
}
but will be throwed to the caller of this method.
A FileNotFoundException is a checked exception, meaning that you must be able to recover from it, i. e. display a message like The file could not be opened. Users frequently delete files, hence, you cannot be sure that the file you are requesting actually exists. However, it would be a really bad experience for the user if your application crashed only due to the file not being present.
For that reason, the compiler forces you to handle the case that the file you are requesting does not exist. Most probably, you should only display some kind of error message to the user and log the exception maybe.
I found this explanation of checked exceptions to be very helpful in case you have further questions.
I am new to android apps development. Recently,Im writing an application which able to show public ip based on Ipify. So far, i already:
Download the required jar file and put inside libs folder
I also compile file within gradle
Then i import required class it to my class
How to use Ipify, according to its website:
import org.ipify.Ipify;
public class HelloIP {
public static void main(String[] args) throws IOException {
System.out.println(Ipify.getPublicIp());
}
}
I write the following method to be invoked from another class:
public static String getPublicIp() throws IOException{
String ip = Ipify.getPublicIp();
return ip;
}
Another Class
//Get wifi
getWifiName wifiInfo = new getWifiName();
String myIP = wifiInfo.getPublicIp();
However, i keep getting:
Error:(52, 43) error: unreported exception IOException; must be caught
or declared to be thrown
I tried to modify the code and use the following try and catch, but still got the same error.
public static String getPublicIp() throws IOException{
String myip = Ipify.getPublicIp();
try{
return myip;
}
catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
}
Im not too good in catch and throw exception, and already spent the whole day for this.I dont have idea anymore to fix this error..T.T
public static String getPublicIp() {
try{
return Ipify.getPublicIp();
}catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
return null;
}
In case it didn't help, clean project in your IDE. You may have some data cached and it might be a reason.
Your problem is in another class! As you have declared the method getPublicIp() to throw IOException that class is afraid of receiving the Exception and therefor requests catching it.
In Java you have two types of Exceptions. Checked and unchecked. Checked Exceptions must be caught.
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.
Unchecked Exceptions are those which extend RunTimeException. They are used for marking unexpected states usually caused by user's input. They shouldn't cause harm and should be worked out with business logic. You don't have to catch them, but sometimes you should.
On the other hand there are Checked Exceptions which mark dangerous situations. For example the application being unable to open a file. As those situations are found dangerous, you must catch them.
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
or using the fact, that they all extend Exception:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
or since Java 7:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};
I'm writing a custom sonar rule for java using java. I encountered an assertion error which can not be fixed easily. I'm sure that the source code is correct. But the test case can not be passed. I wonder what should I care about when using TDD process and how can I fix it.
public class logTCheckFile {
private static Logger logger = Logger.getLogger(logTCheckFile.class);
public void loggingWithID(String nonsense) throws myException{
logger.error("errorID:20160801 this is an error");
return;
}
public void loggingWithoutID(String nonsens){
try{
logger.error("this is an error");
}catch(NullPointerException e){
logger.error("what",e);
}
return;
}
public void specific(){
logger.error("only the logger");
try{
logger.error("this is an error");
}catch(NullPointerException e){
logger.error("without an exception");
}
return;
}
}
I'm testing the file above, I wrote a rule to test whether the exception, which is not thrown, is printed in the logger.
The message is AssertionError: Unexpected at [20](here is a picture of the failure stack trace)
The code I wrote to check the file is as follows:
public class logTCheck extends IssuableSubscriptionVisitor {
Logger log = Logger.getLogger(logTCheck.class);
#Override
public List<Kind> nodesToVisit() {
return ImmutableList.of(Kind.METHOD);
}
#Override
public void visitNode(Tree tree){
MethodTree method = (MethodTree) tree;
if(method.throwsClauses().size()==0){
log.info("this method does not have a throw clause");
BlockTree bt = method.block();
for(StatementTree st:bt.body()){
if(st.is(Kind.TRY_STATEMENT)){
TryStatementTree tst = (TryStatementTree) st;
for(CatchTree ct:tst.catches()){
for(StatementTree state:ct.block().body()){
ExpressionStatementTree ex = (ExpressionStatementTree)state;
MethodInvocationTree mit = (MethodInvocationTree) ex.expression();
if(mit.arguments().size()!=2){
log.error(method.simpleName());
reportIssue(method.simpleName(), "you didn't print the exception in the log");
}
}
}
}
}
};
}
}
The message is AssertionError: Unexpected at [20]
This means that line 20 of the test data contains a violation of the rule you are checking.
You need to tell the validator that this violation is intentionally there.
An easy way to do this is to add a comment like this on the line right before the violation:
// Noncompliant#+1 {{the violation message}}
The #+1 means that the violation is on the next line.
Adjust the number appropriately.
The comment must be at the beginning of the line,
or there may be whitespace in front of the //.
The violation message enclosed within {{...}} is optional, but highly recommended.
When doing TDD,
an easy way to enter the correct message is to add something like {{x}} which will cause the test to fail,
and then you can copy the message from the test output into the test file to fix it.
I finally found the problem from another answer from Michael. I didn't tell the tester where the issue should be. I should use the comment// Noncompliant to mark out the issue.
I have a a method that is being called from Main but when the time comes to call the static method within it will not proceed and test stops.
I have inserted log comments in order to tell where the problem is and no exceptions are caught so there is no compiling nor runtime errors so far.
The static method that is not being called is GC2CommonMethods.loadApplication();.
The weird thing is that when running Main from Eclipse IDE it runs perfectly but it does not when executing from jar file through the same Main method.
See below both codes from the method that is being executed and the detail of the static method that is within a static class respectively.
I would appreciate your help with this. Thanks.
//This method is intented to be called from Main method
package com.mycompany.test.loginRoleEntitlements;
public void verifyLoginPageElements() {
logger.info("\t1.0/1.0.2 - Verif**strong text**ying Login page elements...");
try {
logger.info("entering Try");
GC2CommonMethods.loadApplication(sl); //Static method from Static class.
assertTrue("Region identifier is not present.", sl.isElementPresent(PageAttributes.LoginPage.DB_LABEL));
assertTrue("Forgot Password link is not present", sl.isElementPresent(PageAttributes.LoginPage.FORGOT_PASSWORD));
} catch (SeleniumException se) {
logger.info("caught SeleniumException");
logger.error(se.getMessage());
throw se;
} catch (AssertionFailedError ae) {
logger.info("caught AssertionException");
logger.error(ae.getMessage());
throw ae;
} catch (Exception e) {
logger.info("caught Exception");
logger.info("Encountered exception");
e.printStackTrace();
}
//This is the static method that is within GC2CommonMethods static class
package com.mycompay.common;
public static void loadApplication(SeleniumHandle sl) {
sl.open(props.getProperty("APPLICATION_URL"));
sl.waitForPageToLoad("30000");
assertEquals("The page is not the correct one.
|Expected: "+PageAttributes.LoginPage.LOGINPAGE_TITLE + ".
Found:"+sl.getTitle(),PageAttributes.LoginPage.LOGINPAGE_TITLE,sl.getTitle());
}
I found the solution. The problem was on the main method when trying to read a properties file. There was an uncaught exception which was not being logged so I was not able tell where the problem was. Thanks for your replies.
I've read this: Can I use throws in constructor? -- which gave me the right idea, and led me to one answer, but was not very explicit. I've also read several others, but could not find my answer. To recap what I've learned for context, essentially, this will not compile...
public ExampleClass(String FileName)
{
this(new FileInputStream(FileName));
}
public ExampleClass(FileInputStream FileStream)
{
DoSomethingToSetupBasedUponFileStream(FileStream);
}
...because the FileInputStream constructor (called from the String Constructor) may throw a FileNotFoundException. You can still create the constructor by making it throw the same exception as follows:
public ExampleClass(String FileName) throws FileNotFoundException
{
this(new FileInputStream(FileName));
}
My question is related to a default constructor (no arguments) that would simply use a default filename String constant:
public ExampleClass() throws FileNotFoundException
{
this(DEFAULT_FILE_NAME);
}
This would chain the constructors as:
ExampleClass() --> ExampleClass(<String>) --> ExampleClass(<InputFileStream>)
In a case like this, is it possible to use a default value (static final class member) in the default constructor, to instantiate (further down the chain) a FileInputStream, but not have to use the throws FileNotFoundException code (which would require someone using the class to either re-throw or handle the exception?
If I could do something like the following, I would handle the exception myself:
public ExampleClass()
{
try
{
this(DEFAULT_FILE_NAME);
}
catch (Exception e)
{
DoSomethingToHandleException(e);
}
}
...However, as far as I know this is not possible, because the "Constructor call must be the first statement in a constructor"
Being more used to .Net at this point, I've never been forced to deal with exceptions if I didn't really want to... :D
Refactor your file construction code out of your constructor, so you could do something like this --
public ExampleClass() {
try {
fileInputStreamMethod(DEFAULT_FILE);
}
catch(Exception e) {
...
}
public ExampleClass(String fileName) throws Exception {
fileInputStreamMethod(fileName);
}
private void fileInputStreamMethod(String fileName) throws Exception {
// your file handling methods
}
You are correct that you cannot catch an exception from the call to this(...).
You could use a static method to produce what you want:
static ExampleClass createDefault()
{
try
{
return new ExampleClass(DEFAULT_FILE_NAME);
}
catch(Exception e)
{
DoSomethingToHandleException(e)
}
}
You could do something like this:
public ExampleClass(String FileName)
{
this(getStream(FileName));
}
private static FileInputStream getStream(String name) {
try {
return new FileInputStream(name);
} catch (Exception e) {
// log error
return null;
}
}
The real question is, why would you not want to throw an exception? How should your program behave if the file cannot be opened? I think it would be unusual that you would want it to proceed as if there were no problem. Quite likely, the null input stream will cause grief later on.
In general, you're better off throwing an exception as close to the source of an error as possible.
Basically what you have to do is do the work that your constructor has to do in a different method(something that's not a constructor) and then use it in the default constructor. But am not sure how useful this technique is in your scenario.
cheers!