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
}
Related
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 do not know how to successfully try and catch the exception. As you can see I already started the try-catch statement but do not know how to finish it. I get the error " tractorException.java:83: error: unreported exception tractorException; must be caught or declared to be thrown
setVehicleID(0); "
import java.io.*;
import java.util.*;
import javax.swing.*;
public class tractorException extends Exception {
protected int VehicleID;
public int setVehicleID(int VehicleID) throws tractorException {
if (VehicleID <= 0 || VehicleID > 100000) {
throw new tractorException();
} else {
this.VehicleID = VehicleID;
return this.VehicleID;
}
}
public int getVehicleID() {
return this.VehicleID;
}
tractorException() {
setVehicleID(0);
}
public static void main (String[] args) {
try {
throw new Exception("Something went wrong!!");
} catch (Exception e) {
}
Change your main method to:
public static void main (String[] args) {
try {
throw new tractorException(); // infinite loop ensues
} catch (Exception e) {
// this catch doesn't matter
}
}
The infinite loop occurs because tractorException's constructor calls setVehicleID(0), which in turn calls throw new tractorException(), which, as you guessed, calls setVehicleID(0) ... to infinity and beyond.
A function that throws exception must be caught or declared to be thrown. The issue you have with your code is in the line setVehicleID(0); as stated in the error log you posted.
Since setVehicleID() method throws exception, any time you call this function, it must be caught or re-throw. To fix your error, you need to surround this call with try catch:
tractorException()
{
try{
setVehicleID(0);
}
catch( tractorException e ) {
// Do something with error
}
}
try enter this
you cannot call Directly setVehicleID method because it is risky Method
tractorException() {
try{
setVehicleID(0);
}catch(Exception e){
}
}
In my quest to learn Java better, I have been trying to understand exception handling. I cannot understand why the following code fails to compile.
The compiler message is:
TestExceptionHandling.java:12: error: exception StupidException is never thrown in body of corresponding try statement
catch (StupidException stupidEx) {
^
In the try block, method exTest.doExTest() is called. In this method I catch an InterruptedException and in its catch block I throw a new StupidException.
So why does the compiler say it's not thrown? What am I missing? Can any expert help me see my mistake please?
public class TestExceptionHandling {
public static void main(String argv[]) {
String output = "";
try {
output = "\nCalling method doExTest:\n";
exTest.doExTest();
}
catch (StupidException stupidEx) {
System.out.println("\nJust caught a StupidException:\n " + stupidEx.toString());
}
System.out.println(output);
}
}
class exTest {
static long mainThreadId;
protected static void doExTest() { //throws StupidException
mainThreadId = Thread.currentThread().getId();
Thread t = new Thread(){
public void run(){
System.out.println("Now in run method, going to waste time counting etc. then interrupt main thread.");
// Keep the cpu busy for a while, so other thread gets going...
for (int i = 0; i < Integer.MAX_VALUE; i++) {
int iBoxed = (int)new Integer(String.valueOf(i));
String s = new String("This is a string" + String.valueOf(iBoxed));
}
// find thread to interrupt...
Thread[] threads = new Thread[0];
Thread.enumerate(threads);
for (Thread h: threads) {
if (h.getId() == mainThreadId) {
h.interrupt();
}
}
}
};
t.start();
try {
Thread.sleep(5000);
}
catch (InterruptedException e){
System.out.println("\nAn InterruptedException " + e.toString() + " has occurred. Exiting...");
throw new StupidException("Got an InterruptedException ", e); // ("Got an InterruptedException. Mutated to StupidException and throwing from doExTest to caller...", e);
}
}
}
class StupidException extends Exception {
public StupidException(String message, Throwable t) {
super(message + " " + t.toString());
}
public String toString() {
return "Stupid Exception: " + super.toString();
}
}
Methods need to explicitly declare that they throw exceptions (with the exception of runtime exceptions, which are a bit different). Try declaring your doExTest method as
protected static void doExTest() throws StupidException {
...
}
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
}
}