Java Catch Multiple Exceptions, Rethrow Exception


In Java 7, get square has been improved to deal with numerous special cases in a solitary catch square. In the event that you are getting numerous exemptions and they have comparative code, at that point utilizing this element will decrease code duplication. How about we comprehend java get various special cases include with an example.

Java get different exceptions

p>Before Java 7, we used to get different special cases one by one as appeared/p>
 

catch (IOException ex) { 

logger.error(ex); 

throw new MyException(ex.getMessage()); 

catch (SQLException ex) { 

logger.error(ex); 

throw new MyException(ex.getMessage()); 

} 

In Java 7, we can get both these exemptions in a solitary catch square as:

 

catch(IOException | SQLException ex){ 

logger.error(ex); 

throw new MyException(ex.getMessage()); 

} 

If a catch square handles various special cases, you can isolate them utilizing a pipe (|) and for this situation, exemption parameter (ex) is conclusive, so you can't transform it. The byte code produced by this component is littler and lessen code redundancy.

Java rethrow exception

Another improvement is done in Compiler analysis of rethrown exceptions. Java rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration.

Let’s see this with a small example:


package com.journaldev.util;

public class Java7MultipleExceptions {

	public static void main(String[] args) {
		try{
			rethrow("abc");
		}catch(FirstException | SecondException | ThirdException e){
			//below assignment will throw compile time exception since e is final
			//e = new Exception();
			System.out.println(e.getMessage());
		}
	}

	static void rethrow(String s) throws FirstException, SecondException,
			ThirdException {
		try {
			if (s.equals("First"))
				throw new FirstException("First");
			else if (s.equals("Second"))
				throw new SecondException("Second");
			else
				throw new ThirdException("Third");
		} catch (Exception e) {
			//below assignment disables the improved rethrow exception type checking feature of Java 7
			// e=new ThirdException();
			throw e;
		}
	}

	static class FirstException extends Exception {

		public FirstException(String msg) {
			super(msg);
		}
	}

	static class SecondException extends Exception {

		public SecondException(String msg) {
			super(msg);
		}
	}

	static class ThirdException extends Exception {

		public ThirdException(String msg) {
			super(msg);
		}
	}

}

As you can see that in rethrow strategy, get square is getting Exception however it's not part of tosses provision. Java 7 compiler examine the total attempt square to check what sorts of special cases are tossed and afterward rethrown from the catch square.

Note that this investigation is impaired in the event that you change the catch square argument.

Further Reading:Exception Handling in Java .






© Journaldev Python 3 tutorial spring tutorial