Custom exception in java - java

I have a simple exception and I don't know how to deal with it. My question is what should I do in main?
I know I should create an Exception Class but that's a simple example to understand how should the exceptions be treated in main.
In main I want do display a message and exit the program and I don't understand how to do it.
public void addProfessor() throws Exception {
if(professor) {
throw new Exception(" prof already exists");
}
else {
professor=true;
System.out.println("\n--- addProfessor ---");
System.out.println("Professor: " + professor);
superState=SuperState.OPEN;
System.out.println(superState);
subState=SubState.ASSIGNED;
System.out.println(subState);
}
}
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch(Exception e) {
e.printStackTrace();
}
finally {
}

First of all your example looks like the exception you are trying to use is thrown in standard buisness flow.
It's good practice to keep exceptions to handle really exceptional cases, and not use it in a program flow.
If it's just an example then:
First: (as mentioned in one of comments) better create your own exception (just derive for example from RuntimeException if you want unchecked
or from Exception for checked one) - then you will not catch some other unexpected exception by accident.
Second: when you catch the exception then you have a choice what to do:
do some cleanup & rethrow
just log it
you can also re-try if it makes sense (in your example it does not, because re-trying will just throw another exception - unless the profesor has been removed by another thread)
When you catch the exceptin instead of e.printStackTrace(); you can get a message from the exception or even (as you created your own meaningful exception) you already know the root cause and can just display it to the user.
just an ilustration:
catch(ProfessorAlreadyExistsException e) {
System.out.println("Professor already exists");
}

To create a custom Exception you need to create a class that extends Exception. For example as follow:
public class ProfessorException extends Exception {
public ProfessorException(String msg) {
super(msg);
}
}
Then you need to use this ProfessorException in your code:
public void addProfessor() throws ProfessorException {
if(professor) {
throw new ProfessorException(" prof already exists");
}
...
}
...
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
e.printStackTrace();
} finally { // Note that finally block is not needed here because it does nothing
}
If you want to display a message on standard output instead of printing the stack trace you can do that:
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
System.out.println(e.getMessage());
}

Related

What does it mean by propagating all exceptions in Java [duplicate]

I am a C programmer and just learning some java recently because I am developing one android application. Currently I am in a situation. Following is the one.
public Class ClassA{
public ClassA();
public void MyMethod(){
try{
//Some code here which can throw exceptions
}
catch(ExceptionType1 Excp1){
//Here I want to show one alert Dialog box for the exception occured for the user.
//but I am not able to show dialog in this context. So I want to propagate it
//to the caller of this method.
}
catch(ExceptionType2 Excp2){
//Here I want to show one alert Dialog box for the exception occured for the user.
//but I am not able to show dialog in this context. So I want to propagate it
//to the caller of this method.
}
}
}
Now I wan to use call the method MyMethod() somewhere else in another class. If some one can provide me some code snippet how to propagate the exceptions to the caller of MyMethod() so that I can display them in a dialog box in the caller method.
Sorry If I am not so much clear and weird in the way of asking this question.
Just don't catch the exception in the first place, and change your method declaration so that it can propagate them:
public void myMethod() throws ExceptionType1, ExceptionType2 {
// Some code here which can throw exceptions
}
If you need to take some action and then propagate, you can rethrow it:
public void myMethod() throws ExceptionType1, ExceptionType2 {
try {
// Some code here which can throw exceptions
} catch (ExceptionType1 e) {
log(e);
throw e;
}
}
Here ExceptionType2 isn't caught at all - it'll just propagate up automatically. ExceptionType1 is caught, logged, and then rethrown.
It's not a good idea to have catch blocks which just rethrow an exception - unless there's some subtle reason (e.g. to prevent a more general catch block from handling it) you should normally just remove the catch block instead.
Don't catch it and rethrow again. Just do this and catch it in the place you want
public void myMethod() throws ExceptionType1, ExceptionType2 {
// other code
}
Example
public void someMethod() {
try {
myMethod();
} catch (ExceptionType1 ex) {
// show your dialog
} catch (ExceptionType2 ex) {
// show your dialog
}
}
Just rethrow the exception
throw Excp1;
You will need to add the exception type to the MyMthod() declaration like this
public void MyMethod() throws ExceptionType1, ExceptionType2 {
try{
//Some code here which can throw exceptions
}
catch(ExceptionType1 Excp1){
throw Excp1;
}
catch(ExceptionType2 Excp2){
throw Excp2;
}
}
Or just omit the try at all since you are no longer handling the exceptions, unless you put some extra code in the catch statements doing things with the exception before rethrowing it.
I always do it like this :
public void MyMethod() throws Exception
{
//code here
if(something is wrong)
throw new Exception("Something wrong");
}
then when you call the function
try{
MyMethod();
}catch(Exception e){
System.out.println(e.getMessage());
}

How is multiple exception handling done in java? [duplicate]

This question already has answers here:
Exception Handling with Multiple catch block [duplicate]
(2 answers)
Can I catch multiple Java exceptions in the same catch clause?
(10 answers)
Closed 4 years ago.
i have below piece of code which in my spring boot applicatin. This piece of code does email validation,
class EmailValidation {
public static void validate(List<String> s){
try {
for (String address : s) {
if (s == null || s.indexOf("#") < 0) {
throw new InvalidEmailAddressException("Email address is invalid ");
}
new InternetAddress(s);
}
} catch(AddressException e){
LOGGER.Error("Please validate email addresses");
}
}
}
class InvalidEmailAddressException extends RuntimeException {
public InvalidEmailAddressException(String message) {
super(message)
}
}
My question is how do I catch InvalidEmailAddressException? How can i achieve it to handle the exception in this piece of code itself and how it will be handled by the caller?
Use the multi-catch block like so:
try {
stuff
} catch (AddressException | InvalidEmailAddressException ex) {
handle exception
}
There're 2 types of exceptions: checked, unchecked.
InvalidEmailAddressException extends RuntimeException which is unchecked exception that you shouldn't catch, so better extend it from Exception class.
As an alternative to SnakeyHips' answer, you can provide several catch blocks separately, like
try {
// do what you have to do here
} catch (AddressException) {
LOGGER.Error("AddressException thrown");
} catch (InvalidEmailAddressException ex) {
LOGGER.Error("InvalidEmailAddressException thrown");
}
Firstly I think it is not good practice to extend from RuntimeException, that exception means that program crashes, you should extend from Exception. My opinion you should read some more about exceptions in Java. If your method does not catch exception you should put in method signature that method throws specific exception, something like:
public static void validate(List s) throws InvalidEmailAddressException {
... }
Then make this one:
class InvalidEmailAddressException extends Exception{
public InvalidEmailAddressException(String message){
super(message)
}
And that catch method, about AddressException you do not have it definition here, and I think if you want this to be proceed to caller you should not catch it at all, just declare in throws.
SnakeyHips' answer is solid but be aware that you will not able to react differently to different exceptions.
try {
//your code
} catch (AddressException e1) {
//handle this exception
} catch (InvalidAdressException e2) {
//handle this exception
}
This will enable you to handle the exceptions differently. If you dont care about this you may aswell just catch the general Exception class:
try {
//your code
} catch (Exception e) {
//handle exception
}

Java Exceptions check in main()

I have java project contains around 10-15 java files and number of classes. I want to return exit code 1 from catch block inside the main() if any exception occurred any where through out these programs. However all of the classes has exception catch blocks so that exceptions will be handled there itself and catch block inside main() cannot "see" it.
Is there any way to check whether any exception occurred anywhere in the project inside main() of start point without change any code in other files but only at start point.
Thanks
Noushad
You can't. You need to modify the other classes to throw an exception to the caller so that you can catch the exception in main and return the exit code you want.
Write a common "logging" function and call it from any relevant catch block. If you need to exit the program, use System.exit.
public class Defines {
public static LogException(Exception exception) {
...
if (ShouldExitFromException(exception))
System.exit(1);
}
}
elsewhere in your code:
try {
// some code
} catch (Exception exception) {
Defines.LogException(exception);
}
But it will depend what your other catch blocks are actually doing, and to be honest, this all sounds like a bad idea. Logging exceptions might be ok, so you know where and when they're happening, but exiting the program for even ones that have been handled properly is not a good idea.
Throw exception from all methods of all classes and catch it in Main method's catch block. Log exception and then do exit.
public static void main(String[] args)
{
try
{
ClassA.methodX();
ClassB.method();
}
catch(Exception e) //use specific exception class
{
e.printsttrace();
System.exit(1);
}
}
Class A
class classA
{
public static void methodX() throws Exception
{
try{
//perform some operation
}catch(Exception e)
{
//throw exception from here.
}
}

(Java) Try-catching specific lines of code vs Try-catching the whole function

So I'm working on a little project in Java and I've come down to the main method and I'm unsure how I should handle try-catching exceptions correctly.
Should I be:
Try-catching specific lines of code that I know will probably throw an exception?
Like:
public class Stuff {
public static void main(String[] args) {
try {
// code that will probably throw exception 1 or 2
} catch (exception1 e) {
// handle exception 1
} catch (exception2 e) {
// handle exception 2
}
//rest of code that probably won't throw any exceptions
}
}
OR
Try-catching the whole main method even if some of the code in the try block will not throw an exception? Like:
public class Stuff {
public static void main(String[] args) {
try {
// code that will probably throw exception 1 or 2
// rest of code that probably won't throw any exceptions
} catch (exception1 e) {
// handle exception 1
} catch (exception2 e) {
// handle exception 2
}
}
}
One thing to consider is whether or not the code running after the catch block would still be valid if an exception was thrown. For example, consider the following method:
private void readFile()
{
List<String> lines = null;
try
{
lines = Files.readAllLines(Paths.get("/to/my/file.txt"));
}
catch (IOException e)
{
// log exception...
}
for (String line : lines)
{
System.out.println(line);
}
}
If readAllLines throws that IOException, then the code after the catch block will throw a NullPointerException.
There's a bigger question of deciding when to catch vs re-throw an exception. I answer it by asking myself this question:
"Can my method fulfill its contract if this exception is thrown?"
YES: Handle the exception and continue to fulfill the method's contract.
NO: Re-throw the exception (either in throws clause or wrap in a more appropriate exception type).
For example, with this method,
public static List<String> readAllLines(Path path) throws IOException
if the file does not exist, it cannot return a list of the lines of the file, so it throws an IOException.
On the other hand, this method
public static boolean deleteIfExists(Path path) throws IOException
does not throw an exception if the file does not exist (it instead returns the boolean to tell you what happened). One way to think of the contract of this method is, "after this method executes, there will not be a file at path". So in this case, if the file does not exist, the contract is still fulfilled.
That depends - should the non-exceptional code be executed if either exception is raised? This isn't a "best practices" question, this is a "what are your specifications?" question.
Suppose your code looks like this:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
someValue = defaultValue;
}
// Continue, possibly using the default value
In a case like this, you should wrap only the single line. On the other hand, maybe your code looks like this:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
log.fatal("The universe is crashing! Run for your lives!");
System.exit();
}
// Continue, assuming that parsing succeeded
In that case, it's a stylistic choice. Either approach is valid, though with such an extreme failure as in this example it might be better to simply declare that the method throws something and forget the try/catch entirely. In fact, whatever your handling code is, if the only thing left for your method to do after it is to bail out, you should consider omitting the try/catch and using a throws clause instead.
This third case, however, is objectively wrong:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
log.info("something strange happened");
// Don't bother the calling code with the exception, it can't handle it.
}
// Continue, assuming that parsing succeeded
In a case like that, the continuation code must go inside the try block.

Disrupting the flow of a program if an error is caught?

Ok I have a method that kicks off an object that deasl with data - a kind of factory.
The factory splits data and sends the data that is split to custom objects that further process/refine the data.
My problem is I log errors with an object that basically just appends the strings together into a log of error. Some errors are ok - meaning the flow of program can continue - however some are serious and therefore the process needs to terminate and I need to throw the error log back to the original method. And stop processing the data at that point or it could mess things up.
The original method returns a string you see. I don't have to worry about how the method returns the error just need to get it to it.
Thanks
It sounds like you should be throwing an exception when you hit a serious error and have the call to the factory within a try catch statement to handle the errors it can generate.
Have a look here http://download.oracle.com/javase/tutorial/essential/exceptions/throwing.html for more information.
The basic code would be
Exception e = new Exception();
throw e;
However you could look at creating your own exception class to contain more information about the specific error caused.
Edit: You mention having an error log to return, a custom exception could have this included within it.
Double Edit:
Somthing like
public class BadFactoryException extends Exception{
private String log;
public BadFactoryException(String log){
this.log = log
}
}
With the factory method that can throw it being something like
public returntype factory throws BadFactoryException(input){
try{
//code goes here
}catch(Exception e){
throw new BadFactoryExeption(log);
}
}
You've just described exceptions and exception handling, a feature of Java since day one.
You don't mention Exceptions in your question - do you use them already?
If not, this is exactly what they are made for.
If you do, then you need to rethink how you are catching the exceptions for your logging.
I'm not a Java person, but I think that you need to use a try {...} catch (error) {...} block. When the desired error is caught, run System.exit(). Here's an example:
try {
/* Do your stuff here */
} catch (ExceptionType name) {
/* Oh noes, a fatal error! */
print('Oh noes!');
System.exit()
}
Is this what you were looking for?
Basic tutorial on exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/
And another good article: http://www.javaworld.com/javaworld/jw-07-1998/jw-07-exceptions.html
If you want to devide critical situations of non critical just do this:
try {
// get here all your work
} catch (TerribleException e) {
// log and exit the application
}
and in your work just don't throw any exceptions. Simple log the situation and continue the work. So all you need is to define what situations should stop the execution, then throw some Exception in that place and catch it in the class which launches the work.
Ok this is what I wanted..finally figured it out.
4 classes including a custom exception.
package ExceptionTest;
public class Main {
public static void main(String[] args) {
exceptionTester();
}
private static void exceptionTester(){
try{
new FirstLevelObj().begin();
}
catch(MyException e){
System.out.println("Its worked!");
e.printStackTrace();
}
finally{
System.out.println("Oh young man..This Class doth created the other classes! \nAnd has now thrown the exception!");
}
}
}
package ExceptionTest;
public class FirstLevelObj {
private SecondLevelObj second;
public FirstLevelObj() throws MyException{
}
protected void begin()throws MyException{
try{
second = new SecondLevelObj();
second.start();
}
catch(MyException e){
throw new MyException("This Is The One!");
}
finally{
System.out.println("And finally..");
}
}
}
package ExceptionTest;
public class SecondLevelObj {
public SecondLevelObj(){
}
protected void start() throws MyException{
for(int i = 0; i<10; i ++){
if(i == 6){
System.out.println("Exception should be thrown:");
throw new MyException("An Error Hath Occurred Young Man!");
}
else{
System.out.println(i);
}
}
}
}
package ExceptionTest;
public class MyException extends Exception{
public MyException(String s){
super(s);
}
}

Categories

Resources