I know how to create an exception, but I want to intentionally "break" another class.
Let there be two classes X and Y.
If X is running, how can I create an exception that causes the console to output an exception from Y?
Thanks!
~Java preferred
Edit:
Apparently +MarsAtomic and +Murat K. cannot comprehend English correctly. I asked to throw the exception from ANOTHER class, not the class that is running. I do not understand how people can live in society with such a deficient level of reading comprehension.
throw new RuntimeException();
or
String exceptionMsg = "Error";
throw new RuntimeException(exceptionMsg);
--
public class X
{
public X()
{
Y.CreateException();
//or
Y.CreateException("Error");
}
}
public class Y
{
public static void createException()
{
throw new RuntimeException();
}
public static void createException(String msg)
{
throw new RuntimeException(msg);
}
}
Let there be:
public class thisIsAnException extends Exception{
private Class source;
public thisIsAnException(Class source){
this.source = source;
}
public void setSource(Class source) {
this.source = source;
}
#Override
public String getMessage(){
return "Oh no, there is an exception in: " + source.getName();
}
}
public class Y {
public Y(){
try {
X instanceX = new X();
} catch (thisIsAnException ex) {
ex.setSource(this.getClass());
System.err.println(ex.getMessage());
}
}
public static void main(String[] args){
Y instanceY = new Y();
}
}
public class X {
public X () throws thisIsAnException{
throw new thisIsAnException(this.getClass());
}
}
Is this what you mean?
Related
New to this topic and right now I'm stuck at a brick wall. I have 2 classes, parent class: Controller.java and subclass: GreenhouseControls.java. I need to serialize a GreenhouseControls object but also an instance variable (eventList) from its superclass Controller.java.
My serialization happens when an inner class of GreenhouseControls.java throws a custom ControllerException, which is caught in the main method. Before terminating the program, the GreenhouseControls object should be saved (including the field from its superclass).
Why is a NotSerializableException thrown by the inner class WindowMalfunction of GreenhouseControls? Anyone have any ideas, as I am seriously stuck?
What I tried is the following:
Implement serializable on Controller.java. This is because if the superclass is serializable, then subclass is automatically serializable, however this throws java.io.NotSerializableException: GreenhouseControls$WindowMalfunction, (WindowMalfunction is the inner class that throws the initial exception to begin the serialization processs).
Implement serializable on GreenhouseControls.java and implement custom serialization by overriding writeObject() and readObject() to save the field from the superclass. This approach yet again throws the same exception as the approach 1.
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(super.eventList);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
Object obj = in.readObject();
List<Event> x = cast(obj);
super.eventList = x;
}
Controller.java
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class Controller {
// THIS IS THE VARIABLE I NEED TO SAVE
protected List<Event> eventList = new ArrayList<Event>();
public void addEvent(Event c) {
eventList.add(c);
}
public void run() throws ControllerException {
while (eventList.size() > 0)
// Make a copy so you're not modifying the list
// while you're selecting the elements in it:
for (Event e : new ArrayList<Event>(eventList))
if (e.ready()) {
System.out.println(e);
e.action();
eventList.remove(e);
}
}
public static void shutDown() { }
}
GreenhouseControls.java class (note I have removed the inner classes and other code from it and only left related info)
public class GreenhouseControls extends Controller implements Serializable {
private int errorcode = 0;
public class WindowMalfunction extends Event {
public WindowMalfunction(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
windowok = false;
throw new ControllerException("Window malfunction");
}
public String toString() {
return "Window malfunction";
}
}
public class PowerOut extends Event {
public PowerOut(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
poweron = false;
throw new ControllerException("Power out");
}
public String toString() {
return "Power out";
}
}
// Various other inner classes that extend event exist
public static void serializeObject(GreenhouseControls gc) {
FileOutputStream fileOut;
ObjectOutputStream out;
try {
fileOut = new FileOutputStream("dump.out");
out = new ObjectOutputStream(fileOut);
out.writeObject(gc);
System.out.println("WERRROR code: " + gc.getError());
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(super.eventList);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
Object obj = in.readObject();
List<Event> x = cast(obj);
super.eventList = x;
}
#SuppressWarnings("unchecked")
public static <T extends List<?>> T cast(Object obj) {
return (T) obj;
}
public int getError() {
return errorcode;
}
public Fixable getFixable(int errorcode) {
switch (errorcode) {
case 1:
return new FixWindow();
case 2:
return new PowerOn();
default:
return null;
}
}
public static void main(String[] args) {
GreenhouseControls gc = null;
try {
String option = args[0];
String filename = args[1];
if (!(option.equals("-f")) && !(option.equals("-d"))) {
System.out.println("Invalid option");
printUsage();
}
// gc = new GreenhouseControls();
if (option.equals("-f")) {
gc = new GreenhouseControls();
gc.addEvent(gc.new Restart(0, filename));
}
gc.run();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid number of parameters");
printUsage();
} catch (ControllerException e) {
String errormsg;
if (e.getMessage().equals("Window malfunction")) {
gc.errorcode = 1;
errormsg = "Window malfunction event occurred Error code: " + gc.errorcode;
} else {
gc.errorcode = 2;
errormsg = "Power out event occurred Error code: " + gc.errorcode;
}
logError(errormsg);
serializeObject(gc);
gc.displayEventList();
shutDown();
}
}
}
Event.java
public abstract class Event {
private long eventTime;
protected final long delayTime;
public Event(long delayTime) {
this.delayTime = delayTime;
start();
}
public void start() { // Allows restarting
eventTime = System.currentTimeMillis() + delayTime;
}
public boolean ready() {
return System.currentTimeMillis() >= eventTime;
}
public abstract void action() throws ControllerException;
Event has to be Serializable too.
Change
public abstract class Event {
to
public abstract class Event implements Serializable {
I am new to Java and trying my hands on the exception handling code. Everything was fine to me until I get unhandled exception error. Can anyone please help me to correct the code and tell my mistake so that I can never commit again?
Exception Class - Created this to retrieve message for different exceptions
// Implement user defined exception classes
class InvalidAgeException extends Exception{
public InvalidAgeException(String message) {
super(message);
}
}
class InvalidJobProfileException extends Exception{
public InvalidJobProfileException(String message) {
super(message);
}
}
class InvalidNameException extends Exception{
public InvalidNameException(String message) {
super(message);
}
}
Applicant Class - Class to set and get attributes of Applicant
class Applicant {
private String name;
private String jobProfile;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJobProfile() {
return jobProfile;
}
public void setJobProfile(String jobProfile) {
this.jobProfile = jobProfile;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Validator Class - Class to check if the Applicant has a name or not
class Validator{
//Implement your code here
public boolean validateName(String name) throws Exception
{
if(getName().length()>0)
{
return true;
}
else{
return false;
}
}
public boolean validateJobProfile(String jobProfile) throws Exception
{
if (getJobProfile().equalsIgnoreCase("Associate") || getJobProfile().equalsIgnoreCase("Clerk") ||
getJobProfile().equalsIgnoreCase("Executive") || getJobProfile().equalsIgnoreCase("Officer"))
{
return true;
}
else{
return false;
}
}
public boolean validateAge(int age) throws Exception
{
if(getAge()>=18 && getAge()<=30)
{
return true;
}
else{
return false;
}
}
public void validate(Applicant applicant) throws Exception
{
if(validateName(getName())==false)
{
throw new InvalidNameException("Invalid Name");
}
if (validateJobProfile(getJobProfile())==false)
{
throw new InvalidJobProfileException("Invalid job post");
}
if (validateAge(getAge())==false)
{
throw new InvalidAgeException("Invalid Age");
}
}
}
Tester Class - Main Class where objects of different classes are created
class Tester {
public static void main(String[] args) {
try {
Applicant applicant= new Applicant();
applicant.setName("Jenny");
applicant.setJobProfile("Clerk");
applicant.setAge(25);
Validator validator = new Validator();
validator.validate(applicant);
System.out.println("Application submitted successfully!");
}
catch (InvalidNameException|InvalidJobProfileException|InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}
Your method declares that it throws Exception. Thus, you have to actually catch Exception. If you only want to have to catch either of the three custom exceptions, you need to declare your method as only throwing those three via throws InvalidNameException, InvalidJobProfileException, InvalidAgeException
Plus, your validateAge is declared as throwing an exception, but never actually does throw anything.
Your methods need to specify which exceptions they are actually throwing. At the moment you are simply writing that they throw the general Exception, which you then don't catch in your main.
Change
public void validate(Applicant applicant) throws Exception{...}
to
public void validate(Applicant applicant) throws InvalidNameException, InvalidJobProfileException, InvalidAgeException{...}
For the other methods you need to do it similarly.
In the problem I have to check whether a string is equal to "India" or not. If they are not equal then I have to throw an exception "No Match Exception"
I am creating a class nomatchexception and from constructor I am passing a string "America". Then I am checking whether it equals to "India" or not. If both are equal then printing "Matched" otherwise throwing the exception using throw.
class nomatchexception {
String s;
nomatchexception(String s) {
this.s = s;
if (s.equals("India")) {
System.out.print("Matched!\n");
} else {
throw new NoMatchException("Not Matched!\n");
}
}
}
class nomatchex {
public static void main(String[] a) {
nomatchexception v = new nomatchexception("America");
}
}
Error:
nomatchex.java:9: error: cannot find symbol
throw new NoMatchException("Not Matched!\n");
^
symbol: class NoMatchException
location: class nomatchexception
1 error
You have a class nomatchexception that raises your exception, but NoMatchException excepction class does not exist in your code and is not part of java.
It's required to create a class NoMatchException extending exception and with the proper overrides like:
class NoMatchException extends Exception {
public NoMatchException(String message){
super(message);
}
}
And now you are able to raise your NoMatchException exceptions.
Also for good coding is recommended to use the proper case and naming in the classes maybe your nomatchexception class must be calle IndiaAssertComparer or similar.
Complete example:
class NoMatchException extends Exception {
public NoMatchException(String message){
super(message);
}
}
class IndiaAssertComparer {
private String s;
IndiaAssertComparer(String s) throws NoMatchException {
this.s = s;
if (s.equals("India")) {
System.out.print("Matched!\n");
} else {
throw new NoMatchException("Not Matched!\n");
}
}
}
class NoMatcher {
public static void main(String[] a) throws NoMatchException {
IndiaAssertComparer v = new IndiaAssertComparer("America");
}
}
Create a user defined exception named “NoMatchException” that is fired when the string entered by the user is not “india”.
import java.util.Scanner;
class NoMatchException extends Exception{
String s1;
NoMatchException(String s2)
{
this.s1=s2;
}
public String toString()
{
return s1;
}
public static void main(String[] args) {
String s3;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a string");
s3=sc.nextLine();
try {
if(!"india".equalsIgnoreCase(s3))
throw new NoMatchException("NoMatch
Exceptioncaught!!!");
else {
System.out.println("String matched!!!");
}
}
catch(NoMatchException e) {
System.out.println(e);
}
}
}
I am working on some workflow and it is possible to raise many exceptions in that. I heard that we can keep all those possible exceptions in an Enum (Exception1, Exception2 ...) and use it. How can we do that using Enums in Java?
You can add the classes of exceptions with
enum EnumWithExceptions {
ENUM1(Exception1.class, Exception2.class),
ENUM2(Exception3.class);
private final Class<? extends Exception>[] exceptions;
private EnumWithExceptions(Class<? extends Exception>... exceptions) {
this.exceptions = exceptions;
}
public boolean matches(Exception e) {
for(Class<? extends Exception> e2: exceptions)
if (e2.isInstance(e)) return true;
return false;
}
}
} catch(Exception e){
if (ENUM1.matches(e)){
//do something
} else if(ENUM2.matches(e)) {
//do something
} else {
//do something
}
}
enum Fred {
SAM(AnException.class),
I(AnotherException.class),
AM(YetAnotherException.class)
;
private Throwable t;
Fred(Throwable throwable) {
this.t = throwable;
}
public Throwable getThrowable() {
return t;
}
}
...
throw Fred.SAM.getThrowable();
Why not store the exceptions in an ArrayList? Or if you want to name the index, you could use a HashMap.
import java.util.ArrayList;
import java.util.HashMap;
public final class ExceptionStorage {
private static int exceptionCount = 0;
private static HashMap<String, Exception> indexedExceptions = new HashMap<>();
private static ArrayList<Exception> exceptions = new ArrayList();
public static void addException(Exception e) {
exceptions.add(e);
}
public static void putException(Exception e) {
indexedExceptions.put("Exception" + (++exceptionCount), e);
}
public static ArrayList<Exception> getUnindexedExceptions() {
return this.exceptions;
}
public static HashMap<String, Exception> getIndexedExceptions() {
return this.indexedExceptions;
}
}
Obviously you would have to modify the code to use either ArrayList or HashMap, but I think this would be a better solution than using Enums.
I have defined my own expection class:
public class ProduktException extends Exception {
public ProduktException(String msg){
//null
}
public static void throwProduktNotCreatedException() throws ProduktException {
throw new ProduktException("Cannot be created!");
}
public static void throwProduktNotDeletedException () throws ProduktException {
throw new ProduktException("Cannot be deleted!");
}
}
My Problem is I do not know how to throw them when I try:
try {
...
} catch(ProduktNotDeletedException e) {
e.toString();
}
That does not work... But I want to have these structure! What is wrong?
I appreaciate your answer!!!
UPDATE:
My Problem is, I do not want to create several Exception Klasses I want to have all Exceptions in one class. Is there possibly a solution for that?
If you need to differentiate between different kinds of exceptions, just create 2 different exceptions, maybe something like:
public class ProduktException extends Exception
{
public ProduktException(String msg){
//null
}
}
Then have:
public class ProduktNotDeletedException extends ProduktException
{
....
}
and
public class ProduktNotCreatedException extends ProduktException
{
....
}
Then you can catch one or the other, or both.
try {
...
} catch(ProduktNotDeletedException e1) {
e1.toString();
} catch(ProduktNotCreatedException e2) {
e2.toString();
}
EDIT:
For a single class what I mean is:
public class ProduktException extends Exception {
boolean notDeleted;
boolean notCreated;
public ProduktException(String msg){
super(msg);
}
public boolean isNotDeleted() {
return(notDeleted);
}
public boolean isNotCreated() {
return(notCreated);
}
public static void throwProduktNotCreatedException() throws ProduktException {
ProduktException e = new ProduktException("Cannot be created!");
e.notCreated = true;
throw e;
}
public static void throwProduktNotDeletedException () throws ProduktException {
ProduktException e = new ProduktException("Cannot be deleted!");
e.notDeleted = true;
throw e;
}
}
Then in your try/catch:
try {
...
} catch(ProduktException e) {
e.toString();
if(e.isNotCreated()) {
// do something
}
if(e.isNotDeleted()) {
// do something
}
}
You need to either catch ProduktException, e.g.
try {
...
} catch (ProduktException e) {
e.toString();
}
or declare subtypes, e.g.
public ProduktNotDeletedException extends ProduktException
You'll probably want to pass the message in the constructor up, so add the following in your constructor:
super(msg);
The Syntax given below.
class RangeException extends Exception
{
String msg;
RangeException()
{
msg = new String("Enter a number between 10 and 100");
}
}
public class MyCustomException
{
public static void main (String args [])
{
try
{
int x = 1;
if (x < 10 || x >100) throw new RangeException();
}
catch(RangeException e)
{
System.out.println (e);
}
}
}
What you could do if you don't want to create multiple subclasses of your ProduktException for each different type of exception you need to throw is to include a code in the exception which will let you know what is wrong. Something like this:
public class ProduktException extends Exception {
private Code exceptionCode;
private String message
public ProduktException(Code code, String msg){
this.message = msg;
this.exceptionCode = code;
}
//Getters and setters for exceptionCode and message
}
Code can be an enum so that your application can know that each code corresponds to a specific "problem" (product not created, product not deleted, etc.). You can then throw your exceptions like this
throw new ProduktException(Code.PRODUCT_NOT_CREATED,
"Error while creating product");
And when you catch it you can differentiate based on the code.
catch (ProduktException ex) {
if (ex.getExceptionCode().equals(Code.PRODUCT_NOT_CREATED)) {
...
}
else {
...
}
}