Consider this snippet of code which you might want to write:
public void createTempFileForKey(String key) { Map<String, File> tempFiles = new ConcurrentHashMap<>(); //does not compile because it throws an IOException!! tempFiles.computeIfAbsent(key, k -> File.createTempFile(key, ".tmp")); }
For it to compile you need to catch the exception which leaves you with this code:
public void createTempFileForKey(String key) { Map<String, File> tempFiles = new ConcurrentHashMap<>(); tempFiles.computeIfAbsent(key, k -> { try { return File.createTempFile(key, ".tmp"); }catch(IOException e) { e.printStackTrace(); return null; } }); }
Although this compiles, the IOException has effectively been swallowed. The user of this method should be informed that an Exception has been thrown.
To address this you could wrap the IOException in a generic RuntimeException as below:
public void createTempFileForKey(String key) throws RuntimeException { Map<String, File> tempFiles = new ConcurrentHashMap<>(); tempFiles.computeIfAbsent(key, k -> { try { return File.createTempFile(key, ".tmp"); }catch(IOException e) { throw new RuntimeException(e); } }); }
This code does throw an Exception but not the actual IOException which was intended to be thrown by the code. It's possible that those in favour of RuntimeExceptions only would be happy with this code especially if the solution could be refined to created a customised IORuntimeException. Nevertheless the way most people code, they would expect their method to be able to throw the checked IOException from the File.createTempFile method.
The natural way to do this is a little convoluted and looks like this:
public void createTempFileForKey(String key) throws IOException{ Map<String, File> tempFiles = new ConcurrentHashMap<>(); try { tempFiles.computeIfAbsent(key, k -> { try { return File.createTempFile(key, ".tmp"); } catch (IOException e) { throw new RuntimeException(e); } }); }catch(RuntimeException e){ if(e.getCause() instanceof IOException){ throw (IOException)e.getCause(); } } }
From inside the lambda, you would have to catch the IOException, wrap it in a RuntimeException and throw that RuntimeException. The lambda would have to catch the RuntimeException unpack and rethrow the IOException. All very ugly indeed!
In an ideal world what we need is to be able to do is to throw the checked exception from within the lambda without having to change the declaration of computeIfAbsent. In other words, to throw a check exception as if it were an runtime exception. But unfortunately Java doesn't let us do that...
That is not unless we cheat! Here are two methods for doing precisely what we want, throwing a checked exception as if it were a runtime exception.
Method 1 - Using generics:
public static void main(String[] args){ doThrow(new IOException()); } static void doThrow(Exception e) { CheckedException.<RuntimeException> doThrow0(e); } static <E extends Exception> void doThrow0(Exception e) throws E { throw (E) e; }
Note that we have create and thrown an IOException without it being declared in the main method.
Method 2 - Using Unsafe:
public static void main(String[] args){ getUnsafe().throwException(new IOException()); } private static Unsafe getUnsafe(){ try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); return (Unsafe) theUnsafe.get(null); } catch (Exception e) { throw new AssertionError(e); } }
Again we have managed to throw an IOException without having declared it in the method.
Whichever method you prefer we are now free to write the original code in this way:
public void createTempFileForKey(String key) throws IOException{ Map<String, File> tempFiles = new ConcurrentHashMap<>(); tempFiles.computeIfAbsent(key, k -> { try { return File.createTempFile(key, ".tmp"); } catch (IOException e) { throw doThrow(e); } }); } private RuntimeException doThrow(Exception e){ getUnsafe().throwException(e); return new RuntimeException(); } private static Unsafe getUnsafe(){ try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); return (Unsafe) theUnsafe.get(null); } catch (Exception e) { throw new AssertionError(e); } }
The doThrow() method would obviously be encapsulated in some utility class leaving your code in createTempFileForKey() pretty clean.
Lombok even has an annotation for this trick:
ReplyDeletehttp://projectlombok.org/features/SneakyThrows.html
Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai
DeleteSpring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.
Spring Training in Chennai
The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
Quite nice trick, but you still have to return null from the computeIfAbsent method.
ReplyDeleteThis is an awesome post. Really very informative and creative contents. This concept is a good way to enhance the knowledge. Excellent post.
ReplyDeleteAre you looking for the best Java training institute in Chennai?
Come and learn with Aorta, the best java training institute in Chennai offering the best platform to learn and get the depth of Java.
java training in chennai
java course in chennai
Our digital marketing course in Chennai is targeted at those who are desirous of taking advantage of career opportunities in digital marketing. Marketing professionals who are presently using traditional marketing to meet their business objectives. Start-ups, Entrepreneurs, Business Owners who desire to make use of online media to improve their business goals and objectives.
ReplyDeleteDigital Marketing Course in Chennai
Digital Marketing Training in Chennai
Online Digital Marketing Training
SEO Training in Chennai
wow great info. i am sure i will share this to my friends and relatives. Thank you very much.
ReplyDeleteOneplus Service Center in Chennai | Oneplus Service Centre | Oneplus Service Center | Oneplus Service Center near me | Oneplus Service Center in velachery | Oneplus Service Chennai
I have a different solution, which I personally find elegant and effective and will be happy to share if you tell me your preferred way to send you the code snippets.
ReplyDeleteCompared to your solution #4 it prints a little more (imnsho) useful information on the error. I tend to handle exceptions as close to the source as possible, and tightly control which info is logged or packed into the exception - and handle them in such a way that the program will continue processing in a meaningful way. It's a matter of taste, and it requires a certain coding style, but I like it a lot, and typically have the log entry tell me exactly what went wrong and where it happened.
Cheers from Berlin.
It is an awesome post really informative and useful content and it is so informative.
ReplyDeleteacte chennai
acte complaints
acte reviews
acte trainer complaints
acte trainer reviews
acte velachery reviews complaints
acte tambaram reviews complaints
acte anna nagar reviews complaints
acte porur reviews complaints
acte omr reviews complaints
Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.
ReplyDeletepython training in chennai
python course in chennai
python online training in chennai
python training in bangalore
python training in hyderabad
python online training
python training
python flask training
python flask online training
python training in coimbatore
python training in chennai
python course in chennai
python online training in chennai
python training in bangalore
python training in hyderabad
python online training
python training
python flask training
python flask online training
python training in coimbatore
You have shared a nice article here. After reading your article I got very much information and It resolved many of my doubts. Thanks for sharing this article here.
ReplyDeleteIELTS Coaching in chennai
German Classes in Chennai
GRE Coaching Classes in Chennai
TOEFL Coaching in Chennai
spoken english classes in chennai | Communication training
I simply want to mention I am just all new to blogging and site-building and truly loved you’re web page. Almost certainly I’m planning to bookmark your site . You really have outstanding stories. Many thanks for revealing your webpage.…
ReplyDeleteAzure Training in Chennai
Azure Training in Bangalore
Azure Training in Hyderabad
Azure Training in Pune
Azure Training | microsoft azure certification | Azure Online Training Course
Azure Online Training
I love cheat codes in games and other applications that allows them, it makes easy for playing and building up characters, also check this out
ReplyDeleteFull Stack Course Chennai
Full Stack Training in Bangalore
Full Stack Course in Bangalore
Full Stack Training in Hyderabad
Full Stack Course in Hyderabad
Full Stack Training
Full Stack Course
Full Stack Online Training
Full Stack Online Course
I like your article very much. It has many useful ideas and suggestions. I thinks it will be more helpful for my research in an efficient manner. Please try to post some more topics as well as possible.
ReplyDeleteSalesforce Training in Chennai
Salesforce Online Training in Chennai
Salesforce Training in Bangalore
Salesforce Training in Hyderabad
Salesforce training in ameerpet
Salesforce Training in Pune
Salesforce Online Training
Salesforce Training
Superb blog post! This blog clearly explains the concept and the information are very useful. I thank for sharing this wonderful content. Keep it up!
ReplyDeleteSoftware Testing Training in Chennai
Software Testing Online Training in Chennai
Software Testing Courses in Chennai
Software Testing Training in Bangalore
Software Testing Training in Hyderabad
Software Testing Training in Coimbatore
Software Testing Training
Software Testing Online Training
77%OFF Coach Outlet Store-Coach Bags Clearance Sale,100% Popular
ReplyDeleteNew & Popular Ray Ban Sunglasses Outlet Store Online,2020-2021 Stylish
Clearance Coach Store | 80%OFF Coach Bags Outlet On Sale Online
Share Best Best Adidas Yeezys Store|100% New & Real Yeezy Boost For Sale
2020 Nike Air For 1 Shoes Outlet For Men & Women, 68-85%OFF Cheap Sale
Official Michael Kors Outlet Store Online,100% Cheap MK Bags Sale
61-82%OFF Air Jordan Shoe Stores|Cheap Jordans Releases,Hot Sale