I have the following code:
class ClassDetails {
private String current_class;
public ClassDetails(String current_class) {
this.current_class = current_class;
}
public void getClassDetails() throws ClassNotFoundException {
try {
Class theClass = Class.forName(current_class);
String name = theClass.getName() ;
System.out.println(name);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
class MMain {
public static void main(String[] args) {
ClassDetails C = new ClassDetails(args[0]);
C.getClassDetails();
}
}
And I have this error in main:
Unhandled exception type ClassNotFoundException
How can I solve this?
Your main method calls the getClassDetails() method, which throws that exception, as the signature shows:
public void getClassDetails() throws ClassNotFoundException
And you aren't catching it, or throwing it in the method, so your code will not compile. So you must either do:
public static void main(String[] args) throws ClassNotFoundException {
ClassDetails C = new ClassDetails(args[0]);
C.getClassDetails();
}
Or:
public static void main(String[] args) {
ClassDetails C = new ClassDetails(args[0]);
try
{
C.getClassDetails();
}
catch(ClassNotFoundException ex)
{
//Add exception handling here
}
}
Related
I need to write a test to verify that when an IOException is thrown by the private method_C, Method_B returns True.
But
public final class A{
public static Boolean Method_B(){
try{
//call a private method C which throws IOException
Method_C
}
catch(final IOException e) {
return Boolean.True
}
}
private static Method_C() throws IOException {
return something;
}
What I tried:
#Test
public void testSomeExceptionOccured() throws IOException {
A Amock = mock(A.class);
doThrow(IOException.class).when(Amock.Method_C(any(),any(),any(),any()));
Boolean x = A.Method_B(some_inputs);
Assert.assertEquals(Boolean.TRUE, x);
}
I am getting compilation errors :
1.Cannot mock a final class
2. Method_C has private access in A
Any suggestions on how this can be rectified?
you are required to use finally in try catch
import java.io.*;
public class Test {
public static Boolean Method_B() {
try {
System.out.println("Main working going..");
File file = new File("./nofile.txt");
FileInputStream fis = new FileInputStream(file);
} catch (IOException e) {
// Exceptiona handling
System.out.println("No file found ");
} catch (Exception e) {
// Exceptiona handling
System.out.println(e);
} finally {
return true;
}
}
public static void main(String args[]) {
if (Test.Method_B()) {
System.out.println("Show true ans");
} else {
System.out.println("Sorry error occure");
}
}
}
I keep getting the following error:
PrintServerV1.java:63: error: unreported exception InterruptedException; must be caught or declared to be thrown
server.printRequest("homework7.txt");
^
PrintServerV1.java:64: error: unreported exception InterruptedException; must be caught or declared to be thrown
server.printRequest("assignment4.txt");
^
PrintServerV1.java:65: error: unreported exception InterruptedException; must be caught or declared to be thrown
server.printRequest("speech.pdf");
And I am pretty sure that I have thrown the error. This error only happens when add the following line: Thread.sleep(1000)
Here is my code:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import static java.lang.System.out;
public class PrintServerV1 implements Runnable {
private static final Queue<String> requests = new LinkedList<String>();
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void printRequest(String s) throws InterruptedException {
lock.lock();
try {
out.println("Adding print request for: " + s);
requests.add(s);
condition.signal();
} finally { lock.unlock(); Thread.sleep(1000);}
}
public void sendRequest() throws InterruptedException {
lock.lock();
try {
while (requests.size() == 0) {
condition.await();
}
out.println("Sending Request to printer");
Thread.sleep(1000);
while (!requests.isEmpty()) {
realPrint(requests.remove());
}
} finally {
lock.unlock();
}
}
private void realPrint(String s) throws InterruptedException {
// do the real work of outputting the string to the screen
out.println("Currently printing: " + s);
Thread.sleep(1000);
}
public void run() {
try {
sendRequest();
} catch (InterruptedException exception) {}
}
public static void main(String[] args) {
PrintServerV1 server = new PrintServerV1();
new Thread(server).start();
server.printRequest("homework7.txt");
server.printRequest("assignment4.txt");
server.printRequest("speech.pdf");
}
}
Because your printRequest method throws an InterruptedException, it must be caught in main, or thrown by main... either one of the following answers ought to work ...
public static void main(String[] args) throws InterruptedException {
PrintServerV1 server = new PrintServerV1();
new Thread(server).start();
server.printRequest("homework7.txt"); // these throw an exception
server.printRequest("assignment4.txt"); // That is "InterruptedException"
server.printRequest("speech.pdf"); // It must be caught, or declared thrown!
// Version 1 declares it thrown (above in method declaration)
}
public static void main(String[] args) {
PrintServerV1 server = new PrintServerV1();
try {
new Thread(server).start();
server.printRequest("homework7.txt");
server.printRequest("assignment4.txt");
server.printRequest("speech.pdf");
catch (InterruptedException e) { e.printStackTrace(); } // Version 2 catches it
}
My current code:
class ThrowDemo
{
static void throwMethod()
{
System.out.println("Inside throwMethod");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwMethod();
}
catch(IllegalAccessException e)
{
System.out.println("Caught"+e);
}
}
}
Upto my knowledge exception thrown by throwMethod must be caught. But why does IllegalAccessException get thrown by throwMethod not caught by the catch?
I have some problems throwing my own exception. Here is the code:
class MyException extends Exception {
private String message;
public MyException(String message) {
this.message = message;
}
#Override
public String toString() {
return "Something went wrong: " + message;
}
}
code where MyException is thrown:
static void expand(String input, String output) throws MyException {
try {
Scanner sc = new Scanner(new File(input));
//do something with scanner
} catch (FileNotFoundException e) {
throw new MyException("File not found!");
}
}
and the main method:
public class Encode {
public static void main(String[] args) throws MyException {
expand("ifiififi.txt", "fjifjif.txt");
System.out.println("ok");
}
the exception is thrown normally, the message is printed normally, but the program is terminated and the "ok" message is not printed out.
Exception in thread "main" Something went wrong: File not found!
at vaje3.Encode.expand(Encode.java:59)
at vaje3.Encode.main(Encode.java:10)
Java Result: 1
You are making life hard on yourself trying to cast a new exception. You dont need to do that, just pass the original up. This is better practice since the FileNotFoundException is a standard error so it is a convention shared by most programmers.
public class Encode {
static void expand(String input, String output)
throws FileNotFoundException
{
Scanner sc = new Scanner(new File(input));//no try catch here or new exception
//just let the original be passed up
//via the throw directive
//Do more here.
}
public static void main(String[] args) {
try{
expand("ifiififi.txt", "fjifjif.txt");
} catch ( FileNotFoundException fnfe ){
System.err.println("Warning File not found");
fnfe.printStackTrace();
}
}
}
I have two files:
NewtonRaphson
public class NewtonRaphson {
public double squareRoot ( double input ) throws NegativeNumber{
if (input < 0.0 ) { throw new NegativeNumber("not allowed to input a negative number");}
else if (input == 0.0) { return 0.0; }
else{
double current = 10.0;
for (int i = 0; i < 10; ++i) {
current = current - (current*current - input)/(2*current);
}
return current;
}
}
public static void main(String[] args){
NewtonRaphson nr = new NewtonRaphson();
System.out.println(nr.squareRoot(2.0));
}
}
and NegativeNumber
public class NegativeNumber extends Exception {
public NegativeNumber(String msg){
super(msg);
}
}
When I compile the first one I get:
NewtonRaphson.java:17: unreported exception NegativeNumber; must be caught or declared to be thrown
System.out.println(nr.squareRoot(2.0));
^
1 error
Could someone help me why?
You're throwing NegativeNumber, but never catching it. What kind of baseball is this?
Add a try-catch to your main method.
public static void main(String[] args){
NewtonRaphson nr = new NewtonRaphson();
try {
System.out.println(nr.squareRoot(2.0));
} catch (NegativeNumber e) {
System.out.println("Be more positive!");
}
}
Or if you never want to catch it (this is not advised):
public static void main(String[] args) throws NegativeNumber {
NewtonRaphson nr = new NewtonRaphson();
System.out.println(nr.squareRoot(2.0));
}
public static void main(String[] args){
try{
NewtonRaphson nr = new NewtonRaphson();
System.out.println(nr.squareRoot(2.0));
}
catch(NegativeNumber e)
{
System.out.println("Exception happend!");
}
}